SQL Server: Is it possible to insert into two tables at the same time?

后端 未结 11 1374
青春惊慌失措
青春惊慌失措 2020-11-22 16:22

My database contains three tables called Object_Table, Data_Table and Link_Table. The link table just contains two columns, the identi

11条回答
  •  温柔的废话
    2020-11-22 16:46

    I want to stress on using

    SET XACT_ABORT ON;
    

    for the MSSQL transaction with multiple sql statements.

    See: https://msdn.microsoft.com/en-us/library/ms188792.aspx They provide a very good example.

    So, the final code should look like the following:

    SET XACT_ABORT ON;
    
    BEGIN TRANSACTION
       DECLARE @DataID int;
       INSERT INTO DataTable (Column1 ...) VALUES (....);
       SELECT @DataID = scope_identity();
       INSERT INTO LinkTable VALUES (@ObjectID, @DataID);
    COMMIT
    

提交回复
热议问题