tags:

views:

64

answers:

4

How do I use an SQL statement to return all rows if the input parameter is empty, otherwise only return rows that match?

My SQL looks like this

where person.personstatusuid = @StatusUID
           AND person.forename != ''
           AND person.location = @Location

but I want basically, person.location = @Location OR @Location is blank

How do I do it? Using CASE WHEN perhaps...

+2  A: 

Just use OR?

where person.personstatusuid = @StatusUID
AND person.forename != ''
AND (person.location = @Location or IsNull(@location,'')='')
Andomar
+1  A: 

You can use a simple OR condition:

where person.personstatusuid = @StatusUID
           AND person.forename != ''
           AND (person.location = @Location OR @Location IS NULL)
Pete OHanlon
+2  A: 
SELECT  *
FROM    mytable
WHERE   person.personstatusuid = @StatusUID
        AND person.forename != ''
        AND person.location = @Location
UNION ALL
SELECT  *
FROM    mytable
WHERE   person.personstatusuid = @StatusUID
        AND person.forename != ''
        AND @Location IS NULL

This solution, unlike using OR, is index friendly: it will optimize away the redundant SELECT and use the index.

See this article in my blog for a similar problem with performance details:

(this is for MySQL, but applicable to SQL Server just as well)

Quassnoi
+1  A: 

If person.location doesn't allow nulls the following will work too...


where person.personstatusuid = @StatusUID
AND person.forename != ''
AND person.location = isnull(@Location,person.location)

This assumes if all rows are required then @Location is passed as null and not an empty string ('')

Craig