Link to home
Start Free TrialLog in
Avatar of sohairzaki2005
sohairzaki2005Flag for United States of America

asked on

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

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
Avatar of Bitsqueezer
Bitsqueezer
Flag of Germany image

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
ASKER CERTIFIED SOLUTION
Avatar of Ephraim Wangoya
Ephraim Wangoya
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial