0

I hit a problem today where I thought, "Hey, this might be a good time to try some Dynamic SQL!" However, I'm having a problem. The simplified version might be...

Declare @Condition VARCHAR(MAX)

SET @Query = 'INSERT INTO #Report_Table 
                        SELECT column1, column2, column3
                        FROM my_table
                        WHERE column4 = ''' + @Condition +''''
SET @Condition = 'Blah'
EXEC(@Query)
SET @Condition = 'OtherBlah'
EXEC(@Query)

However, I've found this doesn't work. It gives me no results when I try. It appears the @Condition variable must be set before the @Query variable. But by doing that, I can't run the @Query multiple times using different @Conditions. Is there some way to do what I want?

1
  • Create a temporary table of conditions (or a CTE) and then use a join... Commented Nov 20, 2013 at 16:06

1 Answer 1

2
CREATE TABLE #Conditions (condition varchar(max))

INSERT #Condition VALUES
('Blah'),
('OtherBlah')

INSERT INTO #Report_Table
SELECT column1,column2,column3
FROM my_table
INNER JOIN #Conditions
  ON column4 = condition
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.