I am having a problem to use a declared table in a dynamic sql statement

sohairzaki2005
sohairzaki2005 used Ask the Experts™
on
I am having a problem to use a declared table in a dynamic sql statement
please see my code I am getting an error saying must declare @id1

declare @id1 table (id int, sp2sectionid int,sp2lessonid int, learningobjectcontent nvarchar(20))

DECLARE  @columnname     nvarchar(50)
declare @mysql nvarchar(1000)
 
--declare the cursor
DECLARE @LearningObject CURSOR
SET @LearningObject =cursor
 FOR

   SELECT  column_name from INFORMATION_SCHEMA.COLUMNS
   where TABLE_CATALOG=’xxxxx’
   and TABLE_NAME =’xxxxxxccccc’
   and substring(column_name,1,7)='BitRef_'

OPEN  @Learningobject
Fetch next
from @LearningObject Into @ColumnName


WHILE @@Fetch_Status = 0

   BEGIN


   set @mysql=N'
  insert into @id1
  (
 
  SP2LessonID,
  SP2SectionID,  
  LearningObjectContent)
  (
   select '
   +''''+substring(@ColumnName,8,30)+''' ,'+'ID ,SectionID ,'+
   @columnname+' from ffffffff where id='+cast(@SP2LessonID as nvarchar(10))+'
   )
  '
 
exec (@mysql)
   
                     
  fetch next
  from @learningObject into @columnname
 

   END

CLOSE @learningobject

DEALLOCATE @learningobject
Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,

you cannot use variables which you declared outside the SQL string in dynamic SQL inside an EXEC command. You must think of it as an independent environment where the assembled SQL command runs.

But you can use the command "sp_executesql" which can be used with parameters so you can supply the dynamic SQL command with external variables. See the help for details about using it.

Cheers,

Christian
Software Engineer
Commented:
try
create table ##id1 (
	id int, 
	sp2sectionid int,
	sp2lessonid int, 
	learningobjectcontent nvarchar(20)
)

DECLARE  @columnname     nvarchar(50) 
declare @mysql nvarchar(1000)
  
--declare the cursor
DECLARE @LearningObject CURSOR
SET @LearningObject =cursor 
 FOR

   SELECT  column_name from INFORMATION_SCHEMA.COLUMNS
   where TABLE_CATALOG=’xxxxx’
   and TABLE_NAME =’xxxxxxccccc’
   and substring(column_name,1,7)='BitRef_'

OPEN  @Learningobject
Fetch next 
from @LearningObject Into @ColumnName


WHILE @@Fetch_Status = 0

   BEGIN


   set @mysql=N'
  insert into ##id1 
  (
  
  SP2LessonID,
  SP2SectionID,  
  LearningObjectContent)
  (
   select '
   +''''+substring(@ColumnName,8,30)+''' ,'+'ID ,SectionID ,'+
   @columnname+' from ffffffff where id='+cast(@SP2LessonID as nvarchar(10))+'
   )
  '
  
exec (@mysql)
   
                      
  fetch next
  from @learningObject into @columnname
  

   END

CLOSE @learningobject

DEALLOCATE @learningobject

drop table ##id1

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial