1
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
4

1 回答 1

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中运行修改。

于 2013-02-22T05:49:20.123 回答