1

我正在尝试使用演示数据更新表,所以我决定构建一个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'.

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

非常感谢!

4

2 回答 2

2

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

 FETCH NEXT FROM BGCursor INTO @BGID, @CreateDate 

代替

 FETCH NEXT BGCursor INTO @BGID, @CreateDate 

有关语法,请参阅MSDN 文章

于 2012-07-10T20:42:51.320 回答
1

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

FETCH NEXT FROM BGCursor INTO @BGID, @CreateDate
于 2012-07-10T20:44:00.057 回答