如何在2015年日期字段中插入所有日期?
问题描述:
我正在使用SQL Server并且有一个包含'date'字段的表格(Table_Date)。我想在此字段中插入所有2015年的日期。如何在2015年日期字段中插入所有日期?
它应该有365重复行,1行中的2015年
答
这里有一种方法:
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
答
一种方法每天是具有递归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;
答
像这样的东西可以工作以及:
declare @count int = 0
while (@count < 365)
begin
--make this the insert
select DATEADD(DD, @count, getdate())
set @count = @count + 1
end
不知道这会应用到,但...这是很基本的,但如果这是什么背景是一次性事件,这不重要。
(日期,不为空)的[我怎样才能从给定的日期范围插入表中的日期( – Sam 2015-01-26 19:42:30
可能重复http://stackoverflow.com/questions/21299773/how-i-can-insert-dates-in-the-table-from-given-date-ranges) – abl 2015-01-26 19:45:56