2015-01-26 96 views
0

我正在使用SQL Server并且有一个包含'date'字段的表格(Table_Date)。我想在此字段中插入所有2015年的日期。如何在2015年日期字段中插入所有日期?

它应该有365重复行,1行中的2015年

+0

(日期,不为空)的[我怎样才能从给定的日期范围插入表中的日期( – Sam 2015-01-26 19:42:30

+0

可能重复http://stackoverflow.com/questions/21299773/how-i-can-insert-dates-in-the-table-from-given-date-ranges) – abl 2015-01-26 19:45:56

回答

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 
+0

注意:更正。 – RBarryYoung 2015-01-26 19:56:48

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; 
+0

谢谢Gordon为我的问题提出了两个解决方案。我试图运行递归CTE,但它给出了以下错误。 Msg 1035,Level 15,State 10,Line 2 'cast'附近语法不正确,预计为'AS'。 Msg 102,Level 15,State 1,Line 6 ')'附近语法不正确。 – Sam 2015-01-26 19:51:28

+0

@Sam。 。 。我把这个类型留给了演员。 – 2015-01-27 22:19:07

+0

谢谢@Gordon。 – Sam 2015-01-29 13:08:22

0

像这样的东西可以工作以及:

declare @count int = 0 

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

不知道这会应用到,但...这是很基本的,但如果这是什么背景是一次性事件,这不重要。