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

?