I have two tables: Defect and DefectData. Each Defect may or may not have one or many DefectData. As such DefectData has a DefectId column as a foreign-key.
The Id in both tables is an autoincrementing identity.
The problem I am having is that when I want to insert a new Defect and its DefectData the Defect is inserted first and gets an Id, but I don't know what that Id is to give to DefectData. My solution is to then select from defects matching inserted开发者_C百科 data to get the Id.
- Insert Defect
- Get that defect's Id
- Insert DefectData(zero or many) with Id from 2.
Setting IdentityInsert on then inserting with my own Id will not work as this is run by a webserver and there might be concurrent calls (Am I right here?).
Thanks in advance.
The basic pattern is this using SCOPE_IDENTITY() to get the new row ID from Defect
BEGIN TRAN
INSERT Defect ()
VALUES (...)
INSERT DefectData (DefectID, AdditionalNotes, ...)
VALUES (SCOPE_IDENTITY(), @AdditionalNotes, ...)
COMMIT TRAN
精彩评论