0

I'm building a dynamic query. Inside it, I have declare variables. Now I want to concatenate this variable in my insert query

declare @qry nvarchar(MAX)
select @qry='Declare @var1 nvarchar(10); set @var1 =''abcd''
insert into mytable (col1) values ('+@var1+')'

When I execute this code it give me an error

Must declare the scalar variable "@var1".

But if I declare @var1 outside @qry then it works fine.I am having problem in concatenating the value of variable.

Please help

Thanks

Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48
Muhammad Taqi
  • 305
  • 2
  • 6
  • 19

1 Answers1

0

You cannot do that. The context of execution of Dynamic query is different from the outer script.

this will work

declare @qry nvarchar(MAX)
Declare @var1 nvarchar(10); 
set @var1 ='abcd'
select @qry='insert into mytable (col1) values ('+@var1+')'
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48