datepart函数在sql azure中不起作用

时间:2013-05-10 14:05:40

标签: sql-server azure-sql-database

我想将日期部分拆分为年份,并将其分配给存储过程中的变量。 我在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)

1 个答案:

答案 0 :(得分:0)

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

;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