Juan Pedro
Juan Pedro

Reputation: 175

Use IF conditional into where clause

I have a query where I want to use something like IF conditional into WHERE clause so I do something like:

 ...
 AND (@City = '%'
         OR [a].[City] LIKE(@City))

So I read this like : IF @City = '%' just continue , if not execute OR clause OR [a].[City] LIKE(@City)

But when I run code results don't return values as I want. What am I doing wrong? am I reading this wrong?

Upvotes: 0

Views: 103

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

You should be able to simply do:

WHERE . . . AND
      [a].[City] LIKE @City

% is the wildcard for LIKE, so CITY LIKE '%' returns all non-NULL values of CITY. This seems to be the intention of using '%' for selecting all cities.

Upvotes: 1

JOHN BENSON LEABRES
JOHN BENSON LEABRES

Reputation: 19

try this on your where clause: WHERE @City = '%' OR [a].[City] LIKE '%' + @City + '%'

Upvotes: 0

sacse
sacse

Reputation: 3744

try like below:

...
 AND (@City = '%'
         OR [a].[City] LIKE('%'+ @City + '%'))

Upvotes: 0

Related Questions