繁体   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