在一个sql while循环中,获取最后一个插入行的id,然后使用OUTPUT将其插入另一个表中?

时间:2012-02-01 22:17:05

标签: sql

我正在使用sql server 2008编写一些sql来循环一些记录。在这个循环中,我需要插入一行,该行的ID将被放入另一个表中现有记录的字段中。我以为我能用OUTPUT实现这个目标,但我找不到一个我想做的事情的例子。

这是我到目前为止所拥有的:

DECLARE @courseTempID INT
DECLARE @courseID INT
DECLARE @academicYearID INT
DECLARE @courseCode VARCHAR(10)
DECLARE @uio_id INT
DECLARE @creatorIntranetUserID INT

WHILE (SELECT count(*) FROM CoursesTemp WHERE dmprocessed = 0) > 0
BEGIN
    SELECT TOP 1 @id = courseTempID FROM CoursesTemp WHERE dmprocessed = 0
    SELECT TOP 1 @academicYearID = academicYearID FROM CoursesTemp WHERE dmprocessed = 0
    SELECT TOP 1 @courseCode = courseCode FROM CoursesTemp WHERE dmprocessed = 0
    SELECT TOP 1 @uio_id = uio_id FROM CoursesTemp WHERE dmprocessed = 0
    SELECT TOP 1 @creatorIntranetUserID = creatorIntranetUserID FROM CoursesTemp WHERE dmprocessed = 0

    INSERT INTO dbo.Courses VALUES(3,@academicYearID,1,@courseCode,@uio_id,GETDATE(),@creatorIntranetUserID)

    OUTPUT INSERTED.courseID INTO @courseID 

    UPDATE CoursesTemp SET dmprocessed = 1, courseID = @courseID WHERE courseTempID = @courseTempID

END

我得到的错误是“INSERTED'附近的语法不正确”。

有人可以帮我解决如何以这种方式使用OUTPUT吗?

3 个答案:

答案 0 :(得分:3)

应用了一些性能改进。使用SCOPE_IDENTITY()

更安全
DECLARE @courseTempID INT
DECLARE @courseID INT
DECLARE @academicYearID INT
DECLARE @courseCode VARCHAR(10)
DECLARE @uio_id INT
DECLARE @creatorIntranetUserID INT
DECLARE @id INT

WHILE EXISTS(SELECT 1 FROM CoursesTemp WHERE dmprocessed = 0)
BEGIN
    SELECT TOP 1 @id = courseTempID 
        ,@academicYearID = academicYearID
        ,@courseCode = courseCode
        ,@uio_id = uio_id
        ,@creatorIntranetUserID = creatorIntranetUserID 
    FROM CoursesTemp WHERE dmprocessed = 0

    INSERT INTO dbo.Courses VALUES(3,@academicYearID,1,@courseCode,@uio_id,GETDATE(),@creatorIntranetUserID)
    UPDATE CoursesTemp SET dmprocessed = 1, courseID = SCOPE_IDENTITY() WHERE courseTempID = @courseTempID
END

答案 1 :(得分:1)

OUTPUT需要介于INSERT INTO dbo.CoursesVALUES(...)之间 你也有OUTPUT INSERTED.courseID INTO @CourseId但@CourseId是一个int变量,它需要是你要插入的表。

编辑我重读了你想要做的事情。您可以将最后一行更改为

,而不是使用OUTPUT
UPDATE CoursesTemp SET dmprocessed = 1, courseId = SCOPE_IDENTITY() 
WHERE courseTempID = @courseTempID

答案 2 :(得分:0)

您可以使用@@ IDENTITY来检索最后插入的ID值。 http://msdn.microsoft.com/en-us/library/ms187342.aspx