sql server - How to create dynamic SQL queries inside CURSOR -


i have dynamically create query inside cursor

declare @id varchar(10)  declare @loc varchar(25) set @loc = '/mainitem/subitem';  declare @query varchar(max)       declare mycursor cursor local fast_forward     select * @tempcolumnname  open mycursor fetch next mycursor @id  while @@fetch_status = 0  begin     set @query = 'select * openxml(@hdoc, '+@loc+', 3) (code_db_key int)'     exec (@query)          fetch next mycursor @id end 

but executing throws exception

msg 137, level 15, state 2, line 1
must declare scalar variable "@hdoc"

msg 319, level 15, state 1, line 1
incorrect syntax near keyword 'with'.

if statement common table expression, xmlnamespaces clause or change tracking context clause, previous statement
must terminated semicolon.`

but when executing same query outside cursor, working fine.

in cursor have again execute xml file , xml output declaration.

declare @id varchar(25)  declare @loc varchar(25) set @loc = '/mainitem/subitem';  declare @query varchar(max)   declare mycursor cursor local fast_forward      select * @tempcolumnname  open mycursor fetch next mycursor @id  while @@fetch_status = 0  begin     set @query = 'declare @hdoc int;                exec sp_xml_preparedocument @hdoc output,'''+ @info+'''         select statement         insert statement exec (@query)            fetch next mycursor @id        end  close mycursor deallocate mycursor 

Comments