SueRobbins
Programmer
I'd like to know if it's possible to have a stored procedure that uses a local variable to dynamically build a WHERE clause then use that variable in a SELECT statement.
Here's the scenario: Five parameters (@a, @b, @c, @d, @e) are passed to the stored procedure. They represent values to be searched for in columns 1, 2, 3, 4, 5 of a table, respectively. The WHERE clause of the select statement should include a column only if the corresponding parameter has a non-blank value.
So, if there are non-blank values for @a and @c, and the values of the other three parameters are blank, then the select statement should be:
SELECT * from table1 WHERE column1 = @a AND column3 = @c
I'd need a LOT (5 factorial) of different select statements to make this work, so I'm hoping a local variable could be used to build up the WHERE clause, then use it.
Something like:
declare @whereString varchar
set @whereString = ''
if @a <> '' then set @whereString = 'column1 = @a '
if @b <> '' then
begin
if @whereString <> '' then set @whereString += 'and '
set @whereString += 'column2 = @b '
end
if @c <> '' then
begin
if @whereString <> '' then set @whereString += 'and '
set @whereString += 'column3 = @c '
end
Same code for @d and @e.
Now, is there a way to use the @whereString in a select statement?
SELECT * from table1 WHERE @whereString ???
Maybe I'm heading in a wrong direction? Hope someone can help. Thanks.
Here's the scenario: Five parameters (@a, @b, @c, @d, @e) are passed to the stored procedure. They represent values to be searched for in columns 1, 2, 3, 4, 5 of a table, respectively. The WHERE clause of the select statement should include a column only if the corresponding parameter has a non-blank value.
So, if there are non-blank values for @a and @c, and the values of the other three parameters are blank, then the select statement should be:
SELECT * from table1 WHERE column1 = @a AND column3 = @c
I'd need a LOT (5 factorial) of different select statements to make this work, so I'm hoping a local variable could be used to build up the WHERE clause, then use it.
Something like:
declare @whereString varchar
set @whereString = ''
if @a <> '' then set @whereString = 'column1 = @a '
if @b <> '' then
begin
if @whereString <> '' then set @whereString += 'and '
set @whereString += 'column2 = @b '
end
if @c <> '' then
begin
if @whereString <> '' then set @whereString += 'and '
set @whereString += 'column3 = @c '
end
Same code for @d and @e.
Now, is there a way to use the @whereString in a select statement?
SELECT * from table1 WHERE @whereString ???
Maybe I'm heading in a wrong direction? Hope someone can help. Thanks.