从插入的FirstTable获取Id

时间:2017-03-27 13:56:58

标签: sql-server

我有这个例子,我需要插入(按钮点击后)一行到FirstTable,在RelationTable中插入两行。来自RelationTable的两行需要为外键FirstTableId获取刚插入行的FirstTableId值。

enter image description here

INSERT INTO FirstTable(atribute) VALUES ('example');
INSERT INTO Relation(RelationDetail, SecondTableId, FirstTableId) VALUES('something', some value , ???);
INSERT INTO Relation(RelationDetail, SecondTableId, FirstTableId) VALUES('something', some value , ???);

1 个答案:

答案 0 :(得分:0)

执行插入后只需使用SCOPE_IDENTITY()

DECLARE @Id INT

INSERT INTO FirstTable(atribute) VALUES ('example');
SELECT @Id = SCOPE_IDENTITY()
INSERT INTO Relation(RelationDetail, SecondTableId, FirstTableId) VALUES('something', some value , ???);
INSERT INTO Relation(RelationDetail, SecondTableId, FirstTableId) VALUES('something', some value , ???);