外键无法创建

Nic*_*rre 24 sql-server constraints foreign-keys foreign-key-relationship

我想在2个表之间使用外键,所以我像往常一样尝试它.现在我遇到的问题是他无法创建,并且由于它的外观它无法创建,因为已经有一个键但是没有.

- Unable to create relationship 
 'FK_tbl_Paramed_RegistratieBehandelingen_Users'.  
  The ALTER TABLE statement conflicted with the 
  FOREIGN KEY constraint "FK_tbl_Paramed_RegistratieBehandelingen_Users". 
  The conflict occurred in database "Nestor_Server", 
  table "dbo.Users", column 'UserID'.
Run Code Online (Sandbox Code Playgroud)

我检查过他们是否有相同的类型,他们做(bigint)所以不明白为什么他不会创建它

pra*_*een 51

您可能在RegistratieBehandelingen(不确定表名称)中有记录,这些记录在用户表中不存在.

select * from RegistratieBehandelingen a where UserID IS NULL or
not exists (select 1 from Users b where b.UserID= a.UserID)
Run Code Online (Sandbox Code Playgroud)

  • 是的,一个零值滑落了网,这就是为什么它不断失败的原因。谢谢 (2认同)

cjk*_*cjk 11

这意味着您的子数据没有匹配的父ID.

运行以下命令以查看是否有任何结果:

SELECT * 
FROM tbl_Paramed_RegistratieBehandelingen r
LEFT JOIN Users u on r.UserID = u.UserID
WHERE u.UserID IS NULL
Run Code Online (Sandbox Code Playgroud)

(在适当的情况下更改表和列名称)

如果您得到任何结果,那么它应该显示哪些记录包含与用户不匹配的UserID.