千家信息网

NULL的陷阱:Merge

发表于:2026-10-31 作者:千家信息网编辑
千家信息网最后更新 2026年10月31日,NULL表示unknown,不确定值,所以任何值(包括null值)和NULL值比较都是不可知的,在on子句,where子句,Merge或case的when子句中,任何值和null比较的结果都是fals
千家信息网最后更新 2026年10月31日NULL的陷阱:Merge

NULL表示unknown,不确定值,所以任何值(包括null值)和NULL值比较都是不可知的,在on子句,where子句,Merge或case的when子句中,任何值和null比较的结果都是false,这就是NULL设下的陷阱,我被坑过。

有一次,我使用Merge同步数据,由于target表中存在null值,虽然在source表中对null值做过处理,但是忽略了target表中的null值,导致数据merge失败。

step1,创建示例数据

--create source tablecreate table dbo.dt_source(id int null,code int null)on [primary]with(data_compression=page)--create target tablecreate table dbo.dt_target(id int null,code int null)on [primary]with(data_compression=page)

step2,插入示例数据

示例数据中,Source表和Target表中都存在null值,不管是在Source表,还是在Target表,都要避免和null值进行比较。

--insert data into tableinsert into dbo.dt_source(id,code)values(1,1),(2,2),(3,null)insert into dbo.dt_target(id,code)values(1,1),(2,null)


step3,错误写法:只处理Source表中的null,而忽略Target表中的null

-- -1 stand for unknwon valuemerge dbo.dt_target tusing dbo.dt_source s    on t.id=s.idwhen matched and( t.code<>isnull(s.code,-1))    then update        set t.code=s.codewhen not matched    then insert(id,code)    values(s.id,s.code);

查看Target和Srouce表中的数据,数据不同步,不同步的原因是when matched子句之后的and 条件, t.code中存在null值,null值和任何值(包括null值)比较的结果都是unknown,在when子句中视为false。

正确写法1,不管是在target表,还是在source表,只要存在null值,必须进行处理,避免出现和null进行比较的情况。

处理的方式是使用一个值来表示unknwon,如果ID列有效值不可能是负值,那么可以使用-1来代替unknown。因为-1和-1 是相等的,逻辑上就将null值和null值视为相同。

-- -1 stand for unknwon valuemerge dbo.dt_target tusing dbo.dt_source s    on t.id=s.idwhen matched and( isnull(t.code,-1)<>isnull(s.code,-1))    then update        set t.code=s.codewhen not matched    then insert(id,code)    values(s.id,s.code);

正确写法2,在条件子句中,使用is null或 is not null来处理null值。

Tsql 使用is null和is not null来确实是,不是 null。 null is null 的逻辑值是true,other_value is null 为false, other_value is not null 为true。

merge dbo.dt_target tusing dbo.dt_source s    on t.id=s.idwhen matched and( t.code<>s.code or t.code is null or s.code is null)    then update        set t.code=s.codewhen not matched    then insert(id,code)    values(s.id,s.code);


数据 子句 处理 写法 示例 同步 是在 条件 结果 还是 逻辑 陷阱 有效 相同 原因 就是 情况 方式 有效值 负值 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 广州万易互联网科技有限公司 科技互联网政务服务 互联网科技垄断 互联网扶贫科技 沃里互联网科技 互联网 视角下的科技创新 天下捷融互联网科技 哈尔滨秒房互联网科技有限公司 江阴互联网智能科技产品进口 互联网科技人工智能实验室 燊美集互联网科技有限公司 乌鲁木齐新华智原互联网科技学校 内蒙古九一互联网科技 互联网企业科技类企业如何做账 普陀区互联网教育科技管理办法 互联网界的黑科技 兰石爱特工业互联网科技分公司 广州三三互联网科技有限公司 科技和互联网行业的特点 互联网科技创业计划的风险分析 互联网金融科技创新 伴你行互联网科技有限公司 深圳期待互联网科技 中盈科技互联网信息有限公司 宝灵互联网科技有限公司 崇明区互联网教育科技售后服务 996高科技互联网公司 华中科技大学互联网的牛人 银行科技岗属于互联网吗 承德科技产业互联网平台
0