简体   繁体   中英

Get Id from first table in transaction

I got this two tables for example 图片

and I need to made transaction that input data in this tables. How can I get Id that is input in firstTable, and set it as Foreign key FirstTableId in second table?

BEGIN TRANSACTION
INSERT INTO FirsTable (Name) VALUES ('example1')

INSERT INTO SecondTable (Name, FirstTableId) VALUES ('example2', ?)

COMMIT TRANSACTION

Considering id is an identity , Use @@IDENTITY as next:-

BEGIN TRANSACTION
INSERT INTO FirsTable (Name) VALUES ('example1')

INSERT INTO SecondTable (Name, FirstTableId) VALUES ('example2', @@IDENTITY)

COMMIT TRANSACTION 

For More details .

UPDATE:-

For Non identity columns, Use table variable to get id via using Output , as next:-

BEGIN TRANSACTION
DECLARE @id int
DECLARE @table table (id int)

INSERT INTO FirsTable (Name) 
OUTPUT inserted.id into @table
VALUES ('example1')
SELECT @id = id from @table

INSERT INTO SecondTable (Name, FirstTableId) VALUES ('example2',  @id)

COMMIT TRANSACTION

For More details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM