假设我需要复制以下内容
CustID FName SName
1234 Mike Smith
插入后将是
CustID FName SName
1235 Mike Smith
我需要在现有记录和新记录之间创建临时链接。 当我进行插入时,最好有一个带
的临时表ExistCustID New CustomerID
1234 1235
通过这样做,我可以将旧的链接到新的,这是我需要做的,但需要为多行插入完成。
答案 0 :(得分:0)
只需使用SCOPE_IDENTITY()
SELECT
新创建的ID,然后将此INSERT
用于链接表:
-- The Customer you're duplicating
DECLARE @CustID INT
SET @CustID = 1234
-- Insert the copy record
INSERT INTO Customer (FName, SName)
(SELECT FName, SName FROM Customer WHERE CustID = @CustID)
-- Get the last newly inserted ID in the current scope
DECLARE @NewCustID INT
SELECT @NewCustID = SCOPE_IDENTITY()
-- Insert the link record
INSERT INTO [YourLinkTable] (ExistCustID, NewCustomerID)
VALUES(@CustID, @NewCustID)
-- Or if you're updating the master record
UPDATE Customer
SET NewCustomerID = @NewCustID
WHERE CustID = @CustID