开发者

Maintaining a foreign key relationship when inserting into tables with autoincrementing Id's

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.

  1. Insert Defect
  2. Get that defect's Id
  3. 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?).

Maintaining a foreign key relationship when inserting into tables with autoincrementing Id's

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜