I want to select a value into a local variable from a column whose name is also in a local variable.
I set this up:
declare @theID as int, @theIDColumnName as varchar(255), @theSQL as varchar(8000)
@theIDColumnName = 'MyPrimaryKey' -- really this is set elsewhere
set @theSQL = 'Select @theID = i.'+@theIDColumnName+' from inserted i '
execute( @theSQL )
That seems to set @theSQL string correctly, but when I execute it, @theID is an unknown variable, so I get an error:
Msg 137, Level 15, State 1, Line 1 Must declare the scalar variable "@theID".
I realize the local var must be out of scope in the context of the exec, but I'm stumped as to how to solve this. (This is SS 2005, but might need to run on 2000) I've tried a few ideas, but haven't figured it out.
Many thanks to anyone who can help!