NULL 設下的陷阱

來源:互聯網
上載者:User

標籤:

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

 

NULL 設下的陷阱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.