我有一个WHILE循环应该循环30次但由于某种原因它似乎只循环15次.
SQL:
DECLARE @dateInsert date DECLARE @dateLoopTo date DECLARE @cnt INT = 0; SET @dateInsert='2016-01-01' SET @dateLoopTo='2016-01-31' WHILE @cnt <= DATEDIFF (d, @dateInsert , @dateLoopTo ) BEGIN print CONVERT(VARCHAR(10),@dateInsert) + ' '+ CONVERT(VARCHAR(2),@cnt) SET @dateInsert = DATEADD(d, 1,@dateInsert) SET @cnt = @cnt + 1; END
结果:
2016-01-01 0, 2016-01-02 1, 2016-01-03 2, 2016-01-04 3, 2016-01-05 4, 2016-01-06 5, 2016-01-07 6, 2016-01-08 7, 2016-01-09 8, 2016-01-10 9, 2016-01-11 10, 2016-01-12 11, 2016-01-13 12, 2016-01-14 13, 2016-01-15 14,
当我尝试将DATEDIFF(d,@ dateInsert,@ dateLoopTo)更改为30时,SQL似乎可以正常工作.
WHILE @cnt <= 30-- DATEDIFF (d, @dateInsert , @dateLoopTo )
是否有理由返回30的DATEDIFF(d,@ dateInsert,@ dateLoopTo)不起作用?
在每次循环步骤中,您增加两个 cnt
和@DateInsert
.因此,你走过2s.
如何更清楚地编写代码:
WHILE @cnt <= 30