tags:

views:

55

answers:

2

I have a query in sql server 2008. That I want to either pass a value from the dropdownlist or IS NOT NULL (so it shows all of the values). What's the best way to handle this? I know you can't pass the string "IS NOT NULL" to the parameter. I'm a bit stuck on this one.

ASP.NET 3.5 and SQL Server 2008.

+5  A: 

Assuming this is a stored procedure, say your parameter is called @Param1, have the parameter set to NULL to indicate IS NOT NULL, as follows:

SELECT ...
FROM   ...
WHERE  (
           (@Param1 IS NULL AND field1 IS NOT NULL)
           OR (field1 = @Param1)
       )


Suggested by GSerg

Testing ISNULL(@Param1, field1) = field1 with the following:

DECLARE  @test1 nvarchar(10) = 'testing',
         @test2 nvarchar(10) = NULL; -- or 'random' or 'testing'

SELECT   1
WHERE    ISNULL(@test2, @test1) = @test1;

Computations are showing as 1 for each case. This appears to be a better solution than my original answer.

Codesleuth
That's what I said but you said it first and better. +1 to you and -1 answer to me. ;-)
Chris
... which can be simplified to `where isnull(@param, field1) = field1`.
GSerg
Thanks Chris :) You don't deserve a -1. No-one does (that's my philosophy on S.O.)
Codesleuth
@GSerg: Nice simplification. I would check first on the execution plan that when `@param` is `NULL`, the computation for comparing the column is skipped (I have a feeling it isn't).
Codesleuth
... Seems it is skipped. The Actual Execution plan only performs 1 computation in the three possible scenarios. Nice! (I'll add this to the answer)
Codesleuth
Guys, I appreciate it. I didn't know that you can compare a column name to column name. Actually I don't quite understand it. But cool nonetheless.
dotnetN00b
+1  A: 

You can use the like operator:

select * from table1 where name like @param

setting @param to % if you want not null values. But then you have to escape the %.

onof