且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何修复错误'INSERT语句与FOREIGN KEY约束冲突'

更新时间:2023-02-25 21:58:48

你在帖子中粘贴了什么与问题的观点无关。我们需要看到的是你调用的存储过程的DDL,当然还有受影响的表的DDL。



一般来说,如果指定外键约束你有两种方法:如果你在外键字段上允许null,你可以插入null,但如果不是,你需要在插入记录时在该字段中有有效的相关实体主键值。



一个常见问题是当这样的存储过程同时插入两个表时。比你需要先插入引用表,而不是引用引用表。如果引用表的主键是标识类型,则可以使用 @@ IDENTITY 来检索新生成的值。 a> [ ^ ]并将其用于第二个插入语句。
What you have pasted in your post is irrelevant from the problem's point of view. What we need to see is the DDL of the stored procedure you call, and of course the DDL of the tables affected.

In general if you specify foreign key constraint you have two approaches: if you allow null on the foreign key field, you can insert null, but if you don't than you need to have in that field valid related entity primary key value when you insert the record.

A common problem is when such a stored procedure is inserting in both tables at the same time. Than you need first to insert into the referred table, than into the referring one. If the referred table's primary key is of identity type, you can retrieve the newly generated value with @@IDENTITY[^] and use it in the second insert statement.


您尝试插入重复的DistrictId,或者您没有传入数据库中已存在的有效区域的值。



对我来说,这听起来像是没有正确设置DistrictId上的外键关系。
Your trying to either insert a duplicate DistrictId or you're not passing in the value of a valid District that already exists in the database.

To me, this sounds like the foreign key relationship on DistrictId isn't setup correctly.