Avatar of sohairzaki2005
sohairzaki2005
Flag 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
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
Ephraim Wangoya

8/22/2022 - Mon
Bitsqueezer

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
Ephraim Wangoya

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck