用于数据操作任务的游标与基于集合的解决方案

时间:2014-04-03 10:37:02

标签: sql sql-server-2012

我正在阅读有关考试的培训套件-70-461查询SQL Server 2012.

第604页给出了一个例子,我正在测试它,但它不起作用......有什么建议吗?

示例:

IF OBJECT_ID(N'dbo.GetNums', N'IF') IS NOT NULL DROP FUNCTION  dbo.GetNums;
GO

CREATE FUNCTION dbo.GetNums (@low as bigint, @high as bigint) RETURNS TABLE
AS
RETURN
WITH
    L0 as (SELECT c from (VALUES(1), (1)) as D(c)),
    L1 as (SELECT 1 as c FROM L0 as A CROSS JOIN L0 AS B),
    L2 as (SELECT 1 as c FROM L1 as A CROSS JOIN L1 AS B),
    L3 as (SELECT 1 as c FROM L2 as A CROSS JOIN L2 AS B),
    L4 as (SELECT 1 as c FROM L3 as A CROSS JOIN L3 AS B),
    L5 as (SELECT 1 as c FROM L4 as A CROSS JOIN L4 AS B),
    Nums as (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as rownum
            FROM L5)
SELECT @low + rownum - 1 as n
FROM Nums
ORDER BY rownum
OFFSET 0 ROWS 
FETCH FIRST @high - @low + 1 ROWS ONLY;
GO

错误讯息:

  

Msg 102,Level 15,State 1,Procedure GetNums,Line 17
  OFFSET'附近的语法不正确   消息153,级别15,状态2,程序GetNums,第18行
  FETCH语句中选项FIRST的使用无效。

1 个答案:

答案 0 :(得分:2)

上面的代码在SQL Server 2008 R2中运行时会生成错误消息,但在SQL Server 2012中成功运行。

OFFSET和FETCH是new features in 2012