我试图用演示数据更新表格,所以我决定构建一个小小的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
我建造它,以更新表中的日期时间字段。所以我为查询发现的每一行增加一个变量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'.
我很少构建存储过程,所以我有点失落。是否有可能获得有关如何解决这些错误的任何提示?我查看了几个网站来比较我的代码,但找不到任何有用的东西。
非常感谢!
避免光标如果可能的话。改为使用基于集合的操作。 SQL不是过程语言 - 如果你避免使用它,不要在其中使用循环结构。 – Oded 2012-07-10 20:41:20
对于这个特定的错误,问题出在'FETCH NEXT'上,它应该从'BGCursor INTO @BGID,@ CreateDate'中取出。你错过了'FROM' – Lamak 2012-07-10 20:43:51