0

I need to select into a variable using a column name that is also stored in a variable, but it just selects the value of the column name instead.

The code below loops through all of the columns for a table and finds the old and new value of each column (part of a TRIGGER). The problem is, instead of assigning the old and new value to the variables, it assigns the value of the @fieldname variable.

Set @getColumnName = Cursor For
    Select Column_name From Information_Schema.Columns Where Table_Name = @tablename

Open @getColumnName
    Fetch Next From @getColumnName Into @fieldname 

    While @@FETCH_STATUS = 0
    Begin
        Select @oldValue = @fieldname From deleted
        Select @newValue = @fieldname From inserted

        -- Do something with the values here
        -- @oldValue and @newValue are now equal to @fieldname
        -- Actually want them to be the result of the query
    End
Close @getColumnName
2

1 Answer 1

0

Managed to sort this using Dynamic SQL thanks to D Stanley's suggestion

Select * Into #MyInserted From inserted
Select * Into #MyDeleted From deleted

-- New value
Set @SQLString = N'Select @outVar = ' + @fieldname + ' From #MyInserted'
Set @ParmDefinition = N'@outVar varchar(max) Output'

Execute sp_executesql 
    @SQLString, 
    @ParmDefinition, 
    @outVar = @newValue Output;

-- Old value
Set @SQLString = N'Select @outVar = ' + @fieldname + ' From #MyDeleted'

Execute sp_executesql 
    @SQLString, 
    @ParmDefinition, 
    @outVar = @oldValue Output;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.