0

I ran the following query in SQL

declare @h nvarchar(max)
declare @i int
set @i =1
declare @two nvarchar(max)
select @h = 'set @two = (select word from #LocalTempTable where Idcolumn =' + cast(@i as nvarchar(max)) +')'
exec(@h)
print @two

I got the following error

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@two".

Why is this happening?

3
  • Its because the scope of dynamic sql is different than the batch or proc that the variable is declared. Use sp_executeSQL instead, it accepts parameters. You're still going to have a problem referencing #LocalTempTable Commented Jan 9, 2014 at 20:48
  • Thanks Conrad. I changed the exec(@h) to exec sp_executeSQL @h. Still getting the exact same error. Did I make the right change? Commented Jan 9, 2014 at 20:53
  • Are you trying to write dynamic SQL? Commented Jan 9, 2014 at 21:00

2 Answers 2

3

Here is the corrected one. And here is the sqlfiddle.

declare @h nvarchar(max)
declare @i int
set @i =1
declare @two nvarchar(max)
select @h = 'select @to = word from #LocalTempTable where Idcolumn =' + cast(@i as nvarchar(max))
exec sp_executesql @h, N'@to nvarchar(max) output', @to=@two output
print @two
Sign up to request clarification or add additional context in comments.

2 Comments

This was beautiful thank you, I will probably have on more question for you Consult Yarla. Thanks!
Sure, shoot the question is SO, if not me, someone else can also provide answer.-- all the best.
2

You've got an issue with variable scope, @two inside your @h variable is not declared.

You can declare it inside of your @h variable:

DECLARE @h nvarchar(max)
       ,@i INT = 1
SELECT @h = 'declare @two nvarchar(max) set @two = (select ''dog' + CAST(@i as nvarchar(max)) +''')'
EXEC(@h)

You will have a scope issue with the #temp table still, and declaring it inside makes it unavailable outside, so not much point to it.

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.