• Not that many people would notice but you can get the code to be almost a third faster by eliminating the (-1) subtraction. Last but not least, the simplification actually instills a guarantee that you won't have an accidental overrun sometimes caused by the very rare but annoying delay as to when the WHERE clause is executed when you join the results of this function in an external query (Itzik Ben-Gan published that correction to his code just a couple of days after he first published the cascading CTE method used here).

    CREATE FUNCTION dbo.ExplodeDates

    (

    @pStartDate DATETIME

    ,@pEndDate DATETIME

    )

    RETURNS TABLE WITH SCHEMABINDING AS

    RETURN WITH

    E1(N) AS (

    SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1

    )

    , E7(N) AS (SELECT 1 FROM E1 a, E1 b, E1 c, E1 d, E1 e, E1 f, E1 g)

    SELECT TheDate = @pStartDate UNION ALL --This eliminates the need for subtraction on the Row_Number

    SELECT TOP (DATEDIFF(dd,@pStartDate,@pEndDate)) --and addition here

    TheDate = DATEADD(dd,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),@pStartDate)

    FROM E7

    ;

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)