为什么有时出现错误`试图在merge命令上设置一个非NULL-able列的值为NULL`?

Ray*_*phy 5 sql-server sql-server-2008-r2

我使用merge语句来插入新数据或删除数据.我使用temp tableas source和table作为target.

目标表有一个foreign key与另一个表(Table A).

when matched then delete执行(语句)时,有时会遇到以下错误.

error:
    Attempting to set a non-NULL-able column's value to NULL.
Run Code Online (Sandbox Code Playgroud)

如果我评论此行,则查询运行完美.

如果我删除foreign key之间Material tabletable A查询也完美运行.

我已应用此Hotfix但我已经提到了问题.

SQL Server版本:Microsoft SQL Server 2008 R2 (SP1) - 10.50.2550.0 (X64)

**Target Tbale (Material)**                **Table A**

PatientIdRef (ForeignKey)             PatientId(Primary Key)
VisitNumberRef(Foreign Key)           VisitNumber(Primary Key)
Unit_Price                            Name
Unit_Price_Ins                        family
....
....                            

create tabl #Temp 
(
  patinetId [varchar](50) NOT NULL,
  [Visit_Number] [smallint] NULL,
  [Unit_Price] [float] NULL,
  [Unit_Price_Ins] [float] NULL,
  ......
  .....
)
merge materials as target
using(select patinetId ,Visit_Number,Unit_Price,Unit_Price_Ins
from #Temp
) as source
on (source.patientid=target.patientid collate arabic_ci_as and source.visit_number=target.visit_number)
when matched then delete
when not matched then insert
(patinetIdref ,Visit_Numberref,Unit_Price,Unit_Price_Ins )
values(patinetId ,Visit_Number,Unit_Price,Unit_Price_Ins)
Run Code Online (Sandbox Code Playgroud)

Sve*_*tøl 1

由于您在目标表具有多个外键 (FK) 约束的情况下遇到此问题,因此很可能是由于以下错误所致:修复:“尝试将不可为 NULL 的列的值设置为 NULL”错误在 SQL Server 2008、SQL Server 2008 R2 或 SQL Server 2012 中使用 MERGE 语句时出现的消息

您运行的是 SQL Server 2008 R2 SP1 版本 10.50.2550

此问题已在 SQL Server 2008 R2 SP1 版本 10.50.2822 及更高版本(累积更新 8)中修复。

从这里下载:SQL Server 2008 R2 Service Pack 1 的累积更新包 8

或者最好下载适用于 SQL Server 2008 R2 SP1 的最新累积更新:SQL Server 2008 R2 SP1 的累积更新包 13


您提到您已经为此应用了 SQL Server 修补程序之一,但我建议您通过执行SELECT @@VERSION并验证版本号是否为 10.50.2822 或更高版本来仔细检查它是否已正确安装。