我有这个例子,我需要插入(按钮点击后)一行到FirstTable,在RelationTable中插入两行。来自RelationTable的两行需要为外键FirstTableId获取刚插入行的FirstTableId值。
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 , ???);
答案 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 , ???);