views:

178

answers:

4

I need to create a SQL statement that uses the LIKE keyword to filter the result set. Sometimes this value is NULL.

What is the best way to implement in T-SQL? I am using SQL server 2005

+1  A: 

Use coalesce!

COALESCE(filter, '%')

Edit: This is probably the wrong way to do it but I guess it's an option.

Joe Philllips
+4  A: 

Depends what you mean by "not provided". If that means NULL, you can always try

(
    Table.Column LIKE @myParameter
OR
    @myParameter IS NULL
)

I've also found this to sometimes work faster.

ISNULL(Table.Column, @myParameter) = @myParameter

Alternatively, if you dynamically building the TSql from code, just ommit that part of the WHERE clause if you don't have the parameter or populate @myParameter with '%'.

Robin Day
A: 
 SELECT 
 lalala
 WHERE 1=1
 and (
  value like '%'+@search+'%'
  or @search = ''
 )

Although I'm not sure how it will perform...

Tom Ritter
If you have the % either side then it will match everything if @search is '' anyway. In this case you only need the OR if you are doing an exact match.
Robin Day
A: 

Personally, this is the sort of situation where I'd build the SQL statement in the VB/C# code, and just not concatenate the LIKE clause on the end if I didn't have it.

The slightly fancier version of what I just said is to have two versions of a prepared statement, one with and one without the LIKE clause, and call the appropriate one as you need to.

Electrons_Ahoy