UPDATE table1,然后将id插入另一个table2

时间:2016-05-25 19:15:55

标签: sql-server tsql

我想更新MemberTable,然后将这些memberIds带到另一个表中。每次更新成员表时,我都希望更新多个记录。我需要捕获更新成员的每个更新成员ID并插入另一个表。任何正确的建议

这是我到目前为止所尝试的内容。

Declare @memberId int;
  BEGIN TRANSACTION;

BEGIN TRY
   UPDATE [AC]
   SET [AC].LoginName = [ME].Email,@memberId=[ME].MemberId
   FROM Account AS [AC]
   INNER JOIN Member AS [ME] ON [ME].AccountId=[AC].AccountID
   WHERE  year([AC].SignupDate)=2015 AND [AC].LoginName IS NULL 

   --OUTPUT [ME].MemberId INTO 

   INSERT INTO .[dbo].[Tracktable] 
           ([MemberId]
           ,[CompanyId]
           ,[Action]
           ,[DateModified]
           ,[DateProcessed])
     VALUES
           (@memberId,
           null,  
           1,
           GETDATE(),
          null

          )
   END TRY
 BEGIN CATCH
 IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
 END CATCH
 IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;

    GO

1 个答案:

答案 0 :(得分:1)

首先将MemberId存储到临时表中,同样的细节可以插入到Tracktable中。它可以捕获更新成员的每个更新的MemberId并插入Tracktable。

添加内联评论。

BEGIN TRANSACTION;

BEGIN TRY

    -- Storing the MemberId into temporary table,
    -- to store the detail in Tracktable
    SELECT [ME].MemberId INTO #TempForTracking
    FROM Account AS [AC]
    INNER JOIN Member AS [ME] ON [ME].AccountId = [AC].AccountID
    WHERE  year([AC].SignupDate) = 2015 AND [AC].LoginName IS NULL      

    UPDATE [AC]
    SET [AC].LoginName = [ME].Email
    FROM Account AS [AC]
    INNER JOIN Member AS [ME] ON [ME].AccountId = [AC].AccountID
    WHERE  year([AC].SignupDate) = 2015 AND [AC].LoginName IS NULL 

    -- Inserting the MemberId from temp table
    -- into the Tracktable
    INSERT INTO [dbo].[Tracktable] 
           ([MemberId], [CompanyId], [Action], [DateModified], [DateProcessed])
    SELECT MemberId, NULL, 1, GETDATE(), NULL
    FROM #TempForTracking

    DROP TABLE #TempForTracking

END TRY

BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;

END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;

GO