Using a variable for a column name within a query and assign result to another variable...

  • Essentially, I have a stored procedure that contains a cursor which iterates through records within a table that contains table names and column names where to find a certain value that I want to assign to a variable.

    So, in Table1, I have the columns ItemName, TableName, and ColumnName.

    I want to read the values from those three columns into three variables via a cursor. I then want to build a dynamic statement to query the table and column from @TableName and @ColumName and assign the value in that column of that table to a seperate variable.

    Or maybe this makes more sense:

    DECLARE @cn varchar(50)

    DECLARE @value char(1)

    SET @cn = 'MyColumnName'

    EXEC('SELECT TOP 1 @value = ' + @cn + ' FROM TableName')

    I want to have @value = the value of whatever column is specified in the column with the name of @cn in the table called TableName.

    Any ideas?

  • I think I have the gist of what you're asking. Can you supply some specific examples?

    +--------------------------------------------------------------------------------------+
    Check out my blog at https://pianorayk.wordpress.com/

  • Actually, now that I'm re-reading it . . .

    Why are you building a dynamic query? Why not do this:

    DECLARE @cn varchar(50)

    DECLARE @value char(1)

    SET @cn = 'MyColumnName'

    SELECT TOP 1 @value = @cn FROM TableName

    SELECT @value

    +--------------------------------------------------------------------------------------+
    Check out my blog at https://pianorayk.wordpress.com/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply