我正在使用SQL Server並且有一個包含'date'字段的表格(Table_Date)。我想在此字段中插入所有2015年的日期。如何在2015年日期字段中插入所有日期?
它應該有365重複行,1行中的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
注意:更正。 – 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