网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

NULL的陷阱:Merge

    

公司主营业务:成都网站设计、成都网站制作、外贸网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联公司推出新野免费做网站回馈大家。

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

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

step1,创建示例数据

NULL的陷阱:Merge

--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)

NULL的陷阱:Merge

step2,插入示例数据

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

NULL的陷阱:Merge

--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)

NULL的陷阱:Merge


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

NULL的陷阱:Merge

-- -1 stand for unknwon valuemerge dbo.dt_target t
using 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);

NULL的陷阱:Merge

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

NULL的陷阱:Merge

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

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

NULL的陷阱:Merge

-- -1 stand for unknwon valuemerge dbo.dt_target t
using 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);

NULL的陷阱:Merge

正确写法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。

NULL的陷阱:Merge

merge dbo.dt_target t
using 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);

NULL的陷阱:Merge

 


新闻名称:NULL的陷阱:Merge
网页链接:http://bjjierui.cn/article/pccsje.html

其他资讯