Link to home
Start Free TrialLog in
Avatar of lexo
lexo

asked on

Using variable condition on where statement in stored procedure

Please resolve the best way to make this work...

I know the below would never work, I've tried a hlaf dozen solutions including dynamic sql, but this is just the best way to describe what I'm trying to do.

If city not passed as null then I want the query to include it in the where statement.
 
CREATE PROCEDURE sp_CityStateSearch

@City  VarChar(50),
@State VarChar(2)

SELECT *
FROM TABLE
WHERE
State = @State

CASE WHEN @CIty IS NOT NULL THEN
AND City = @City
Else
Avatar of TextReport
TextReport
Flag of United Kingdom of Great Britain and Northern Ireland image

You need to build your SQL as a VarChar variable and then

EXEC (@sql)

Cheers, Andrew
This should work.
CREATE PROCEDURE sp_CityStateSearch
 
@City  VarChar(50),
@State VarChar(2)
 
DECLARE @SQL VARCHAR(8000)
SET @SQL = 'SELECT *
FROM TABLE
WHERE State = ' + CHAR(39) + @State + CHAR(39)
 
CASE WHEN @CIty IS NOT NULL THEN
SET @SQL = @SQL + ' AND City = ' + CHAR(39) + @City + CHAR(39)
END
 
EXEC (@SQL)

Open in new window

Avatar of lexo
lexo

ASKER

TextReport I get the following errors:
Msg 156, Level 15, State 1, Line 20
Incorrect syntax near the keyword 'CASE'.
Msg 156, Level 15, State 1, Line 24
Incorrect syntax near the keyword 'EXEC'.
SOLUTION
Avatar of TextReport
TextReport
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or this
CREATE PROCEDURE sp_CityStateSearch

@City  VarChar(50),
@State VarChar(2)

SELECT *
FROM TABLE
WHERE
State = @State
and ( City = @City or @City is null)
Avatar of lexo

ASKER

Sorry Text report, your solution worked but I like aaparis better because it doesnt use dynamic SQL which can be a pain sometimes.  Thank you both, split points 60/40