SQL Server:WHERE子句与null比较

时间:2014-09-17 14:27:05

标签: sql null case where

我的SP有一个参数@NumeroTransferencia int。 当它不为null时,我需要选择与该变量匹配的行。 但是当它为null时,我必须返回具有H.CodigoTransferencia = null的那些 我尝试了以下但是没有得到好结果:

SELECT 
*
FROM RUTEO.HOJADERUTA H
WHERE 
    (H.CodigoTransferencia IS NULL OR H.CodigoTransferencia = @NumeroTransferencia)

谢谢!

4 个答案:

答案 0 :(得分:1)

你可以试试这个

SELECT 
*
FROM RUTEO.HOJADERUTA H
WHERE 
    (@NumeroTransferencia IS NULL 
       AND H.CodigoTransferencia IS NULL)
 OR (@NumeroTransferencia IS NOT NULL 
      AND H.CodigoTransferencia = @NumeroTransferencia)

答案 1 :(得分:1)

SELECT 
*
FROM RUTEO.HOJADERUTA H
WHERE 
    ((H.CodigoTransferencia IS NULL AND @NumeroTransferencia IS NULL) OR H.CodigoTransferencia = @NumeroTransferencia)

答案 2 :(得分:0)

SELECT *
FROM   RUTEO.HOJADERUTA H
WHERE  (
           @NumeroTransferencia IS NULL 
           AND H.CodigoTransferencia IS NULL
       )
       OR 
       (
           @NumeroTransferencia IS NOT NULL 
           AND H.CodigoTransferencia = @NumeroTransferencia
       )

答案 3 :(得分:0)

SELECT 
*
FROM RUTEO.HOJADERUTA H
WHERE 
    ((@NumeroTransferencia IS NULL OR H.CodigoTransferencia = @NumeroTransferencia) H.CodigoTransferencia IS NULL) 

This will only perform the search if your variable is not null otherwise it will look for H.CodigoTransferencia is equal to your variable otherwise where H.CodigoTransferencia = null