SQL 服务器脚本循环更新并插入到不同的 table 没有光标

SQL Server script loop update and insert to different table without cursor

我正在编写一个简单的 SQL 服务器脚本以从 table 获取 ID 并更新源 table 并使用游标插入另一个 table。

有没有更好的无光标使用方式?

这是我的光标代码:

DECLARE @CourseDelegateId INT;
DECLARE @UserId UNIQUEIDENTIFIER;

DECLARE Invite_Cursor CURSOR FOR
    SELECT CourseDelegateId, UserGuid
    FROM [dbo].[CourseDelegate]
    WHERE StatusTypeId=1 AND EmailSent = 0 AND [Disabled] = 0
    ORDER BY CourseDelegateId

OPEN Invite_Cursor
FETCH NEXT FROM Invite_Cursor INTO @CourseDelegateId, @UserId

WHILE @@FETCH_STATUS = 0
BEGIN
    BEGIN TRANSACTION
       UPDATE [dbo].[CourseDelegate]
       SET EmailSent = 1, NotificationTypeId = 1, Modified= GETUTCDATE()
       WHERE CourseDelegateId = @CourseDelegateId;

        INSERT INTO [dbo].[TrainingNotification]
                   ([CourseDelegateId]
                   ,[UserId]
                   ,[NotificationTypeId]
                   ,[CreatedBy]
                   ,[Created]
                   ,[ModifiedBy]
                   ,[Modified]
                   ,[Disabled])
        VALUES(
            @CourseDelegateId,
            @UserId,
            1,
            ORIGINAL_LOGIN(),
            GETUTCDATE(),
            ORIGINAL_LOGIN(),
            GETUTCDATE(),
            0)

    COMMIT
    FETCH NEXT FROM Invite_Cursor INTO @CourseDelegateId, @UserId
END
CLOSE Invite_Cursor
DEALLOCATE Invite_Cursor

似乎是临时的 table 和 INSERT INTO...SELECT FROM 会容易得多:

SELECT CourseDelegateId,
       UserGuid
INTO #Invites
FROM [dbo].[CourseDelegate]
WHERE StatusTypeId = 1
  AND EmailSent = 0
  AND [Disabled] = 0
ORDER BY CourseDelegateId;

INSERT INTO [dbo].[TrainingNotification] ([CourseDelegateId],
                                          [UserId],
                                          [NotificationTypeId],
                                          [CreatedBy],
                                          [Created],
                                          [ModifiedBy],
                                          [Modified],
                                          [Disabled])
SELECT CourseDelegateId,
       UserGuid,
       1,
       ORIGINAL_LOGIN(),
       GETUTCDATE(),
       ORIGINAL_LOGIN(),
       GETUTCDATE(),
       0
FROM #Invites I;

UPDATE CD
SET EmailSent = 1,
    NotificationTypeId = 1,
    Modified = GETUTCDATE()
FROM [dbo].[CourseDelegate] CD
     JOIN #Invites I ON CD.CourseDelegateId = I.CourseDelegateId;