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

爱⌒轻易说出口 提交于 2019-12-22 08:28:30

问题


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


来源:https://stackoverflow.com/questions/7191589/maintaining-a-foreign-key-relationship-when-inserting-into-tables-with-autoincre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!