Get a list of dates between two dates using a function

前端 未结 21 1332
天涯浪人
天涯浪人 2020-11-22 06:25

My question is similar to this MySQL question, but intended for SQL Server:

Is there a function or a query that will return a list of days between two dates? For exa

21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:41

    Perhaps if you wish to go an easier way, this should do it.

    WITH date_range (calc_date) AS (
        SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP) - 6, 0)
            UNION ALL SELECT DATEADD(DAY, 1, calc_date)
                FROM date_range
                WHERE DATEADD(DAY, 1, calc_date) < CURRENT_TIMESTAMP)
    SELECT calc_date
    FROM date_range;
    

    But the temporary table is a very good approach also. Perhaps shall you also consider a populated calendar table.

提交回复
热议问题