Monday, 9 September 2013

EXEC different queries based on different conditions

EXEC different queries based on different conditions

I have 3 conditions, based on each condition I need to run a separate
query. Something like this:
Declare @p1 varchar, @p2 varchar, @p3 varchar, @q1 varchar, @q2 varchar ,
@q3 varchar
set @q1 = ' select * from foo '
set @q2 = ' select * from foobar '
set @q3 = ' select * from reallyfoobarred '
if @p1 = @p2
begin
EXEC (@q1)
end
if @p1 = 'fish'
begin
exec (@q2)
end
if @p1 = 'cats'
begin
EXEC (@q3)
end
The problem is the variables have to be re-declared and set for each
query. Is there some way to do this with only declaring the variables
once? Where I am at now is thinking about 3 separate stored procs. I don't
want to do that if I don't have to.

No comments:

Post a Comment