Reputation: 35
I have SP that has a parameter @NumeroTransferencia int. I need to select rows that match that variable when it is not null. But when it's null, I have to return the ones which have H.CodigoTransferencia = null I tried the following but I didn't get a good result:
SELECT
*
FROM RUTEO.HOJADERUTA H
WHERE
(H.CodigoTransferencia IS NULL OR H.CodigoTransferencia = @NumeroTransferencia)
Thanks!
Upvotes: 1
Views: 68
Reputation: 3681
You can try this
SELECT
*
FROM RUTEO.HOJADERUTA H
WHERE
(@NumeroTransferencia IS NULL
AND H.CodigoTransferencia IS NULL)
OR (@NumeroTransferencia IS NOT NULL
AND H.CodigoTransferencia = @NumeroTransferencia)
Upvotes: 1
Reputation: 965
SELECT
*
FROM RUTEO.HOJADERUTA H
WHERE
((H.CodigoTransferencia IS NULL AND @NumeroTransferencia IS NULL) OR H.CodigoTransferencia = @NumeroTransferencia)
Upvotes: 1
Reputation: 110
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
Upvotes: 0
Reputation: 18411
SELECT *
FROM RUTEO.HOJADERUTA H
WHERE (
@NumeroTransferencia IS NULL
AND H.CodigoTransferencia IS NULL
)
OR
(
@NumeroTransferencia IS NOT NULL
AND H.CodigoTransferencia = @NumeroTransferencia
)
Upvotes: 0