保存Sql View错误,运行正常,但无法保存“关键字声明附近的错误语法”

时间:2012-11-08 18:50:36

标签: sql

Declare @DaysLeft as INT


;With MyCTE AS
(
    SELECT number + 1 as 'CurrentDay'
    FROM   master..spt_values
    WHERE  type='p'
    AND    number < datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
                                          DateDiff(Month, 0, GETDATE()),0))))
    AND    datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GETDATE()),
                                         number) ) not in ('Saturday','Sunday')
)

Select @DaysLeft = (Select COUNT(*) As MyTotal from MyCTE
WHERE CurrentDay >= DATEPART(DD, GETDATE()))

Select @DaysLeft

1 个答案:

答案 0 :(得分:2)

您无法在视图中声明变量。删除变量并重新定义最终的select语句。

With MyCTE AS
(
    SELECT number + 1 as 'CurrentDay'
    FROM   .spt_values
    WHERE  type='p'
    AND    number < datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
                                          DateDiff(Month, 0, GETDATE()),0))))
    AND    datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GETDATE()),
                                         number) ) not in ('Saturday','Sunday')
)

Select COUNT(*) As DaysLeft from MyCTE
WHERE CurrentDay >= DATEPART(DD, GETDATE())

SQL Fiddle中运行修改。