簡體   English   中英

使用 SCOPE_IDENTITY 插入多個表

[英]Inserting into multiple tables using SCOPE_IDENTITY

我有以下 SQL 代碼用於在我的數據庫中插入新記錄

DECLARE @CustomerID INT
DECLARE @PropertyID INT

BEGIN TRAN T1
    INSERT INTO c_customer (title, f_name, l_name, tel1, tel2, tel3, email, email2, 
                            type, primary_contact, tel1type, tel2type, tel3type) 
    VALUES(@title, @fname, @lname, @tel1, @tel2, @tel3, @email, @email2, 
           'Owner', 1, @teltype1, @teltype2, @teltype3)

    SET @CustomerID = SCOPE_IDENTITY()

    BEGIN TRAN T2
        INSERT INTO c_property (address1, address2, address3, post_code, city, county) 
        VALUES (@address1, @address2, @address3, @postcode, @city, @county)

        SET @PropertyID = SCOPE_IDENTITY()

        UPDATE c_property 
        SET invoice_flag = @PropertyID
        WHERE c_property = @PropertyID

        BEGIN TRAN T3

            INSERT INTO c_customer_assignment 
            VALUES (@PropertyID, @CustomerID)

            COMMIT TRAN T1
            COMMIT TRAN T2
            COMMIT TRAN T3

    SELECT @CustomerID, @PropertyID

這段代碼按我的意願工作,確保使用c_customer_assignment表正確鏈接添加的詳細信息,但是它看起來確實過於復雜,我想知道我是否采取了正確的方法來解決問題(不確定我是否根本需要嵌套事務)。

我知道至少需要一筆交易,因為我確實需要確保記錄不會因其他用戶同時插入而導致不匹配。

我還需要檢查事務隔離,還是這樣就足夠了?

您只需要一筆交易:

DECLARE @CustomerID INT
DECLARE @PropertyID INT

BEGIN TRAN T1

    INSERT INTO c_customer (title, f_name, l_name, tel1, tel2, tel3, email, email2, type, primary_contact, tel1type, tel2type, tel3type) 
    VALUES(@title, @fname, @lname, @tel1, @tel2, @tel3, @email, @email2, 'Owner', 1, @teltype1, @teltype2, @teltype3)

    SET @CustomerID = SCOPE_IDENTITY()

    INSERT INTO c_property (address1, address2, address3, post_code, city, county) 
    VALUES (@address1, @address2, @address3, @postcode, @city, @county)

    SET @PropertyID = SCOPE_IDENTITY()

    UPDATE c_property 
    SET invoice_flag = @PropertyID
    WHERE c_property = @PropertyID

    INSERT INTO c_customer_assignment 
    VALUES (@PropertyID, @CustomerID)

    COMMIT TRAN T1

    SELECT @CustomerID, @PropertyID
Use try catch instead of some many trasactions..

BEGIN TRANSACTION;
BEGIN TRY

---your dml operation should go here
---

END TRY
BEGIN CATCH
   ---CATCH ERROR HERE AND ROLLBACK OPERATIONS HERE


    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM