用光标循环在表的行上

时间:2012-07-10 20:39:29

标签: sql sql-server

我正在尝试使用演示数据更新表格,因此我决定构建一个小stored procedure

这是:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Tommy Bergeron
-- Create date: 2011-07-10
-- Description: This SP updates a Patient's CreateDate row
-- with realistic demo DateTime data.
-- =============================================
CREATE PROCEDURE UpdatePatientCreateDateWithDemoData @PatientID int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    DECLARE @IncrementalDateTime DATETIME,
    @BGID int,
    @CreateDate DATETIME

    -- Setting starting datetime    
    SET @IncrementalDateTime = '2012-01-01 10:00 AM'

    -- Declaring cursor
    DECLARE BGCursor CURSOR FOR
        SELECT BGID, CreateDate FROM G2_BloodGlucose WHERE PatientID = @PatientID ORDER BY CreateDate ASC

    -- Opening cursor and starting the loop
    OPEN BGCursor
    FETCH NEXT BGCursor INTO @BGID, @CreateDate
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Updating row with generated DateTime
        UPDATE G2_BloodGlucose SET CreateDate = @IncrementalDateTime WHERE BGID = @BGID

        -- Incrementing DateTime
        SET @IncrementalDateTime = DATEADD(hour, 1, @IncrementalDateTime)

        FETCH NEXT BGCursor INTO @BGID, @CreateDate
    END

    CLOSE BGCursor
    DEALLOCATE BGCursor

END
GO

我构建它,以更新表中的DateTime字段。因此,对于查询找到的每一行,我将变量增加1小时。

我实际遇到的问题是这些错误:

Msg 102, Level 15, State 1, Procedure UpdatePatientCreateDateWithDemoData, Line 27
Incorrect syntax near 'NEXT'.
Msg 102, Level 15, State 1, Procedure UpdatePatientCreateDateWithDemoData, Line 33
Incorrect syntax near 'NEXT'.

我很少构建存储过程,所以我有点迷失。是否可以获得有关如何解决这些错误的任何提示?我查看了几个网站来比较我的代码,但找不到任何有用的东西。

非常感谢!

2 个答案:

答案 0 :(得分:2)

虽然游标可能是魔鬼的工具,但如果你想使用它们,你需要:

 FETCH NEXT FROM BGCursor INTO @BGID, @CreateDate 

而不是

 FETCH NEXT BGCursor INTO @BGID, @CreateDate 

请参阅MSDN article了解语法。

答案 1 :(得分:1)

我认为您的语法不正确,您缺少FROM关键字

FETCH NEXT FROM BGCursor INTO @BGID, @CreateDate