Maintaining a foreign key relationship when insert

2019-05-08 06:04发布

问题:

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 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?).

Thanks in advance.

回答1:

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