Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Dynamic Query Problem
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01518212
Message ID:
01518213
Views:
52
>I'm trying to run this query:
>
>
>DECLARE @voter_id INT
>SET @Command = 'SELECT @voter_id = voterid FROM tblCamp_CT WHERE VoterId = ' + CAST(@VoterId AS VARCHAR(20)) + ' AND ' + @Query
>EXEC (@Command)
>
>
>and I'm getting the error
>
>
>Must declare the scalar variable "@voter_id".
>
>
>What am I not seeing here???

Yes you didn't declare it :-)
The Dynamic SQL is executed in separate batch and any local variable declared in current batch is not visible there.
You must use sp_executesql:
DECLARE @voter_id INT
SET @Command = 'SELECT @voter_id = voterid FROM tblCamp_CT WHERE VoterId = ' + CAST(@VoterId AS VARCHAR(20)) + ' AND ' + @Query

EXEC sp_executesql @Command, N'@voter_id int OUTPUT', @voter_id = @voter_id OUTPUT
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform