Execute sql text in SQL Server 2005

The following code give an error
 "Msg 2812, Level 16, State 62, Line 5
Could not find stored procedure 'select * from  Lumbartest'."
Is it possible to  execute code that has been placed in a varchar variable?


declare @cmd varchar(100)

set @cmd = 'select * from  Lumbartest'
exec @cmd
LVL 2
Roger AlcindorAsked:
Who is Participating?
 
Roger AlcindorAuthor Commented:
Answered the problem myself :
declare @statement nvarchar(100)

set @statement = 'select * from  Lumbartest'
exec sp_executeSQL @statement
0
 
Roger AlcindorAuthor Commented:
I solved the issue myself
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
or:

exec(@cmd)
0
 
Roger AlcindorAuthor Commented:
Hello angellll,
Unfortunatelt your solution doesn't work.
The code below illustrates this, giving an error message
    Msg 137, Level 15, State 2, Line 1
    Must declare the scalar variable "@testdata".


      declare @testdata float
      declare @testnum int
      declare @secondlabel char(20)
      declare @badgenum int
      declare @statement nvarchar(200)
      declare @dtnow datetime

      set @dtnow = GetDate()
      set @badgenum = 24
      set @secondlabel = 'secondlabel'
      set @testnum = 1
      set @testdata = 2468
      set @statement = 'update LumbarTest set test1result = @testdata,DateTimeTest1 = GetDate(),operator = @badgenum  where Label2 like @secondlabel'

      print @statement
      if @testnum = 1
            exec (@statement)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.