gpt4 book ai didi

sql - 使用 SCOPE_IDENTITY 插入多个表

转载 作者:行者123 更新时间:2023-12-04 14:30:21 25 4
gpt4 key购买 nike

我有以下 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

关于sql - 使用 SCOPE_IDENTITY 插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com