0

我想像年份一样拆分日期部分并将其分配给存储过程中的变量。我在 sql azure 中运行该存储过程。它会抛出错误“此版本的 SQL Server 不支持对 'MASTER..spt_values' 中的数据库和/或服务器名称的引用。

代码:

declare @Year int
SET @Year =DATEPART(YYYY,GETDATE())
create table #SundayDates (Sunday datetime,NextSunday datetime)
INSERT INTO #SundayDates(Sunday,NextSunday)
SELECT max(dates),MAX(DATEADD(DD,+7,dates)) AS last_sunday from
(
    SELECT dateadd(day,number-1,DATEADD(year,@year-1900,0)) AS dates
    FROM MASTER..spt_values WHERE type='p' and
    number between 1 and DATEDIFF(day,DATEADD(year,@year-1900,0),DATEADD(year,@year-1900+1,0))
) as t
WHERE DATENAME(weekday,dates)='sunday' GROUP BY DATEADD(month,datediff(month,0,dates),0)
4

1 回答 1

0

此查询给出相同的结果(作为结果集,而不是插入到临时表中,但可以很容易地适应这样做)并且不依赖spt_values错误消息告诉您不允许的表:

;With Numbers (Num) as (
    select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all
    select 6 union all select 7 union all select 8 union all select 9 union all select 10 union all select 11
), MonthEnds as (
    select DATEADD(month,DATEDIFF(year,'20010101',CURRENT_TIMESTAMP)*12 + n.Num,'20010131') as EndDate
    from Numbers n
), LastSundays as (
    select DATEADD(day,-n.Num,EndDate) as EndDate
    from
        MonthEnds me
            cross join
        Numbers n
    where
        n.Num between 0 and 6 and
        DATEPART(weekday,DATEADD(day,-n.Num,EndDate)) = DATEPART(weekday,'20130512')
)
select EndDate,DATEADD(day,7,EndDate) as FollowingSunday
from LastSundays
于 2013-05-10T14:38:51.287 回答