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
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
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)
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'.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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)
CREATE PROCEDURE sp_CityStateSearch
@City VarChar(50),
@State VarChar(2)
SELECT *
FROM TABLE
WHERE
State = @State
and ( City = @City or @City is null)
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
EXEC (@sql)
Cheers, Andrew