使用SCOPE_IDENTITY

时间:2016-03-14 10:32:30

标签: sql sql-server

我有以下用于在我的数据库中插入新记录的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表正确链接添加的详细信息,但它确实看起来过于复杂,我想知道我是否采取了正确的方法来解决问题(不确定我是否甚至需要嵌套事务)。

我知道至少需要进行一次交易,因为我需要确保记录不会因为其他用户同时插入而导致不匹配。

我是否也需要审查事务隔离,或者这还不够吗?

2 个答案:

答案 0 :(得分:2)

您只需要一笔交易:

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

答案 1 :(得分:0)

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