1. 程式人生 > 其它 >記一次ISNULL()查詢出來雙重資料

記一次ISNULL()查詢出來雙重資料

事情是這樣的,今天查詢前端資料顯示有兩條資料竟然為同一個入庫單號(正常來說應該是唯一的),然後開始排查,使用巢狀查詢時查出來死活有兩條,但是不用巢狀查詢時只有1條,最後順藤摸瓜定位到isnull上,註釋之後只查出來一條,取消註釋後就有兩條。

語法
ISNULL ( check_expression , replacement_value )

說明

如果 check_expression 為 NULL,則返回它的值;否則,將返回後者。

         --兩條   

     SELECT *FROM ( SELECT
tb2.pig_form_id AS FFactory, tb2.MID AS MaterialCode, tb2.NUM, tb2.SWEIGHT AS Weight, 'I' AS TypeName, tb2.INTYPE AS TypeNo, tb2.INTYPENAME AS TypeNameDetail, tb2.INTIME as OutAndPutDate,tb2.LTIME,tb2.VENDORNAME, tb2.FErtificateDate,tb2.FSlaughterDate,tb2.FMaker, ISNULL(tb2.INBILLNO,tb2.Batchno) INBILLNO
FROM dbo.T_asrs_inbill_feedback AS tb2 ) AS A where A.INBILLNO='CPCK--21110701276' --這裡的INBILLNO是tb2.INBILLNO和tb2.Batchno的集合
           --一條(查詢條件只用了一個)
          select top 100*from T_asrs_inbill_feedback where INBILLNO='CPCK--21110701276' --這裡的INBILLNO只是INBILLNO

因為業務需要,我的INBILLNO和Batchno是一樣的,為了防止一個為空而導致整條資料取不到,所以我用了isnull做防範措施。

但是問題就出在這裡,我這樣寫的語法就相當於:

 SELECT
    tb2.pig_form_id AS FFactory,
    tb2.MID AS MaterialCode,
    tb2.NUM,
    tb2.SWEIGHT AS Weight,
    'I' AS TypeName,
    tb2.INTYPE AS TypeNo,
    tb2.INTYPENAME AS TypeNameDetail,
    tb2.INTIME AS OutAndPutDate,
    tb2.LTIME,
    tb2.VENDORNAME,
    tb2.FErtificateDate,
    tb2.FSlaughterDate,
    tb2.FMaker,
        tb2.INBILLNO,
        tb2.Batchno

  FROM
    dbo.T_asrs_inbill_feedback AS tb2 
  WHERE INBILLNO= 'CPCK--21110701276' OR Batchno = 'CPCK--21110701276'

用上述查詢後確定到問題:

問題定位:

資料庫本身存在兩條一模一樣的單號,是因為我的查詢條件不一樣導致!