如何在日期字段中插入2015年的所有日期?

时间:2015-01-26 19:37:16

标签: sql-server date

我正在使用SQL Server,并且有一个表(Table_Date),其中包含' date'领域。我想在此字段中插入所有2015年日期。

它应该有365个不同的行,2015年的每一天都有1行。

3 个答案:

答案 0 :(得分:2)

一种方法是使用递归CTE:

with dates as (
      select cast('2015-01-01' as date) as thedate
      union all
      select dateadd(day, 1, thedate)
      from dates
      where thedate < '2015-12-31'
     )
select *
from dates
option (maxrecursion 0);

另一种方法是使用至少有365行的表。 master..spt_values通常用于此目的:

select dateadd(day, seqnum - 1, '2015-01-01')
from (select row_number() over (order by ()) as seqnum
      from master..spt_values
     ) t
where seqnum <= 365;

答案 1 :(得分:1)

以这种方式:

CREATE TABLE #nums(num INT);
INSERT INTO #nums VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

WITH cteDays AS
(
    SELECT 100*d100.num + 10*d10.num + d1.num AS YearDay
    FROM       #nums AS d1
    CROSS JOIN #nums AS d10
    CROSS JOIN #nums AS d100
    WHERE d100.num <=3
)
SELECT CAST('2015-01-01' AS DATETIME) + YearDay AS YearDate
FROM    cteDays
WHERE   YEAR(CAST( CAST('2015-01-01' AS DATETIME) + YearDay AS DATETIME)) = 2015

答案 2 :(得分:0)

这样的事情也可以起作用:

declare @count int = 0

while (@count < 365)
begin
    --make this the insert
    select DATEADD(DD, @count, getdate())
    set @count = @count + 1
end

不确定这将适用于哪种背景......这是非常基本的,但如果这是一次性事件,那就无所谓了。