需要创建一个带有日期列表的IN子句。该列表需要按降序排列。我创建了一个@cols变量命名,我试图用这个代码来填充它:如何在SQL中使用While循环创建变量
declare @end date='2016/05/30'
declare @begin date = DATEADD(month, DATEDIFF(month, 0, @end), 0) ;
declare @curdate date = @end; -- start on the last day
print @curdate;
print @begin;
DECLARE @cols NVARCHAR (MAX)
while @curdate >[email protected] -- goes from end of the month to beginning of the month
begin
select @cols = @cols + ',[' + CONVERT(NVARCHAR, @curdate, 106) + ']';
select @curdate = DATEADD(DAY,-1,@curdate) -- subtract a day
end
print @cols;
print @curdate;
print @begin;
我希望能获得16年5月30日,16年5月29日,16年5月28日等(正常当然格式化)。代码运行时没有错误,但@cols总是空的。
你应该熟悉一个理货表。你应该在这种情况下使用,而不是循环。 http://www.sqlservercentral.com/articles/T-SQL/62867/ –