日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NULL的陷阱:Merge

發布時間:2023/12/9 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 table create table dbo.dt_source ( id int null, code int null ) on [primary] with(data_compression=page)--create target table create 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 table insert 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 value merge dbo.dt_target t using dbo.dt_source son t.id=s.id when matched and( t.code<>isnull(s.code,-1))then updateset t.code=s.code when not matchedthen 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 value merge dbo.dt_target t using dbo.dt_source son t.id=s.id when matched and( isnull(t.code,-1)<>isnull(s.code,-1))then updateset t.code=s.code when not matchedthen 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 t using dbo.dt_source son t.id=s.id when matched and( t.code<>s.code or t.code is null or s.code is null)then updateset t.code=s.code when not matchedthen insert(id,code)values(s.id,s.code);

?

轉載于:https://www.cnblogs.com/wangsicongde/p/7551284.html

總結

以上是生活随笔為你收集整理的NULL的陷阱:Merge的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。