我使用merge
语句来插入新数据或删除数据。我使用临时表
作为源
,并使用表作为目标
。
目标表与另一个表(表 A
)有一个外键
。
执行(whenmatchedthendelete
语句)时有时会遇到以下错误。
error:
Attempting to set a non-NULL-able column's value to NULL.
如果我评论这一行,查询就会完美运行。
此外,如果我删除 Material 表
和表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)
最佳答案
由于您在目标表具有多个外键 (FK) 约束的情况下遇到此问题,因此很可能是由于此错误所致:FIX: "Attempting to set a non-NULL-able column's value to NULL" error message when you use a MERGE statement in SQL Server 2008, in SQL Server 2008 R2 or in SQL Server 2012
您正在运行 SQL Server 2008 R2 SP1 版本 10.50.2550
此问题已在 SQL Server 2008 R2 SP1 版本 10.50.2822 及更高版本(累积更新 8)中修复。
从这里下载:Cumulative update package 8 for SQL Server 2008 R2 Service Pack 1
或者最好下载适用于 SQL Server 2008 R2 SP1 的最新累积更新:Cumulative update package 13 for SQL Server 2008 R2 SP1
<小时/>您提到您已经为此应用了 SQL Server 修补程序之一,但我建议您通过执行 SELECT @@VERSION
仔细检查它是否已正确安装。并验证版本号是否为 10.50.2822 或更高版本。
关于sql-server - 为什么合并命令有时会出现错误 `Attempting to set a non-NULL-able column' s value to NULL`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26955418/