2

I am trying to create a sql server query select. I have one argument that can be null or not. WHen the @value is null I would like to return all mycolumns with the null value. If value is not null I want to return mycolumns with that value.

How best to handle this, i tried:

SELECT name FROM mytable
WHERE  coalesce( @value,mycolumn)=mycolumn

I got a feeling it lies in the handling of the null value. How can I resolve?

0

4 Answers 4

2
where myColumn = @value or
      (myColumn is null and @value is null)
Sign up to request clarification or add additional context in comments.

Comments

2
SELECT T.name
FROM dbo.mytable T
WHERE
   EXISTS (
      SELECT @value INTERSECT SELECT T.mycolumn
   )
;

2 Comments

This is just brilliant! Couldn't help coming back just to say that.
Thanks, @AndriyM! Make sure you check execution plans. This can work perfectly in many cases, but be wary when you start doing it in complicated queries or with many columns. It can work but you must verify, as I have seen cases where it gets a poor execution plan.
0

1st case. when u pass a city name..

DECLARE @SearchType varchar(80); SET @SearchType = 'Alamo'; Select * From Homes where City = @SearchType OR Coalesce(@SearchType,'') = ''

2nd case. City null or empty.

SET @SearchType = '';

in first case you will get the result by city name. and in 2nd case you will get all the results.

Comments

-1

Try:

SELECT name FROM mytable where myColumn = @value or @value is null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.