SQL Server How to use autogenerated ID from first INSERT in a second INSERT [duplicate]

7vhp5slm  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(144)

This question already has answers here:

How to get the identity of an inserted row? (15 answers)
Closed 17 days ago.

I want to insert data into a table and use the auto-generated ID from the first insert for another table insert.

Currently this is what I have:

Insert into InventoryTransfer (CFromSite, CToSite, CStatus, CUsername)
values ('Store', 'Warehouse', 'Active', 'Chris');

Table InventoryTransfer has a column called CID and it's auto-incrementing. What I currently do is I have to execute

SELECT @@IDENTITY;

and get the value to do the statement below:

Insert into InventoryTransferDetails (CTransferID, CQuantity, CBarcode) 
values (6, 3, '734987598345');

Where 6 is the autogenerated ID I got from SELECT @@IDENTITY; . I'm doing these 3 steps on application level and by that I mean my application has to connect to the server multiple times. How can I do this with just 1 contact with the server?

My logic would be:

Insert into InventoryTransfer (CFromSite, CToSite, CStatus, CUsername)
values ('Store', 'Warehouse', 'Active', 'Chris');

Select @@IDENTITY;

Insert into InventoryTransferDetails (CTransferID, CQuantity, CBarcode) 
values (@@IDENTITY, 3, '734987598345');

Something like the above that would be done in 1 connection with the server. I don't mind using ; as long as it's only 1 connection to the server. Thank you so much.

kr98yfug

kr98yfug1#

You need to store your identity value into a variable between the two inserts: and then use that variable in your second Insert call:

INSERT INTO dbo.InventoryTransfer (CFromSite, CToSite, CStatus, CUsername)
VALUES ('Store', 'Warehouse', 'Active', 'Chris');

DECLARE @IdValue INT = SCOPE_IDENTITY();

INSERT INTO dbo.InventoryTransferDetails (CTransferID, CQuantity, CBarcode) 
VALUES (@IdValue, 3, '734987598345');

相关问题