如何将 2000 年到 2020 年之间的所有日期和所有月份插入 table?

How to insert into a table all dates and all months between year 2000 and 2020?

我在 SQL Server 2008 中创建了一个名为 time_range 的 table,列为

date ID, Month ID, year ID

如何将 2000 年到 2020 年的所有日期、月份、年份批量插入到这些列中?有没有简单的查询可以做到这一点?

请提前帮忙谢谢。

发件人:

1/1/2000  | January  |2000

收件人:

31/12/2020| December | 2020

您可以使用递归 CTE 来执行此操作:

with cte (dateId)
as (
    select cast('2000-01-01' as date)

    union all

    select dateadd(day, 1, dateId)
    from cte
    where dateId < cast('2020-12-31' as date)
    )
select dateId,
    datename(Month, dateId) as monthId,
    year(dateId) as yearId
from cte 
option (maxrecursion 0);  -- to remove the recursion limit

您可以使用它来插入其他 table