我正试图改变下面的观点:
ALTER VIEW [dbo].[Win.v_TodayMin365]
AS
declare @tblOut table(Dates Date)
declare @cnt INT = -365
while @cnt < 0
Begin
set @cnt = @cnt + 1;
insert into @tblOut (Dates) values(cast(dateadd(day,@cnt,getdate()) as Date))
END
select * from @tblOut
deallocate @tblOut
deallocate @cnt
GO
这样的代码工作(如果我突出显示AS和GO之间的所有内容并点击Execute,我得到预期的输出),但我无法将其作为ALTER VIEW运行。然后,我收到以下错误:
关键字'declare'附近的语法不正确。 期待'(',SELECT或WITH
提前感谢任何想法!
答案 0 :(得分:2)
Declare
View
实际上,您不需要使用While
循环。使用计数表技巧生成比while
循环方法
ALTER VIEW [dbo].[Win.v_TodayMin365]
AS
WITH E1(N)
AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1), --10E+1 or 10 rows
E2(N)
AS (SELECT 1 FROM E1 a,E1 b), --10E+2 or 100 rows
E4(N)
AS (SELECT 1 FROM E2 a,E2 b), --10E+4 or 10,000 rows max
calendar
AS (SELECT Dateadd(dd, Row_number()OVER(ORDER BY n), Dateadd(yy, -1, Cast(Getdate() + 1 AS DATE))) AS dates
FROM E4 l)
SELECT *
FROM calendar
WHERE dates <= Cast(Getdate() AS DATE)
这甚至可以转换为Table valued function
或Stored Procedure
。