是否可以使用查询在MS Sql server中添加1月1日至31日之间的所有日期?
如果有人以前做过,请引导我走上正轨。
由于
答案 0 :(得分:2)
DECLARE @dt Date
SET @dt = '2015-01-01'
WHILE @dt < '2016-01-01'
BEGIN
SELECT @dt
--INSERT .....
SET @dt = DATEADD(DAY, 1, @dt)
END
当然这取决于你的表结构
答案 1 :(得分:1)
使用循环我们可以实现这个
Declare @date table(d datetime)
Declare @d datetime, @d1 datetime, @d2 datetime
Declare @inc INT
set @d1='20150101'
set @d2='20151231'
Set @inc = DATEDIFF(D, @d1, @d2)
Set @d = @d1
While @d<=@d2
Begin
Insert into @date values (@d)
set @d=@d+1
End
Select d as DateCol from @date
答案 2 :(得分:1)
这应该可以解决问题:
DECLARE @year int = 2015
;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)-1 FROM N,N a,N b,N c,N d,N e,N f)
SELECT top (datediff(d, cast(@year as char(4)), cast(@year + 1 as char(4))))
CAST(DATEADD(d, N, cast(@year as char(4))) as date)
FROM tally
结果:
2015-01-01
2015-01-02
..
..
2015-12-31