Sql 使用SCOPE\u IDENTITY插入多个表

Sql 使用SCOPE\u IDENTITY插入多个表,sql,sql-server,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)

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

我知道至少需要一个事务,因为我需要确保记录不会因为其他用户同时插入而不匹配

我是否也需要检查事务隔离,或者这就足够了

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 使用try-catch代替一些多个传输。。 开始交易; 开始尝试 ---你的dml行动应该在这里进行 --- 结束尝试 开始捕捉 ---在此处捕获错误并在此处回滚操作 如果@TRANCOUNT>0 回滚事务; 末端捕捉; 如果@TRANCOUNT>0 提交事务; 去
您只需要一个事务:

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

如果
c_客户
c_属性
之间存在M-M关系,则需要3个表。您不需要3个事务。因为任何回滚都会回滚所有3个嵌套事务,所以嵌套事务不会给您带来任何好处,所以我可以删除额外的2个事务吗?这里的表数没有问题。正如您非常正确地指出的,由于M-M关系,所有3个表都是必需的。额外的事务根本不会增加任何好处。看看,真是太棒了,这真的很好地解释了事情。谢谢你!没有任何错误需要捕捉。现在的代码工作得很好,但看起来有点复杂。然后在catch回滚事务中,而不是在三个事务中。