using variable in SELECT statement

  • hi,

    i have 10 tabels of the same structure i want to use SELECT @column_name from @table_name where condition

    here @column name and @table_name are variables which store the column and table name respectively.

    when using this select statement im having problems with variables i.e. its not accepting variables for column or table name

    i want  to make it dynamic so that by jst passing the table and column names it will perform the same operation in different tables.

    is there any solution to this problem

  • try this:

    declare @my_dynamic_query varchar(8000)

    set @my_dynamic_query = 'select [' + @column_name + '] from [' + @table_name + ']

    where [' + @column_name + '] = 23'

    sp_executesql @my_dynamic_query

    Hope that helps,

  • well the problem is not solved. it returns a null value. there is some problem in the querry.

    i need to store the result of the select query in a variable of type int and that query needs to access variables for its column and table names.

    which i have mentioned in my previous post

    viral

  • Hi

    declare @my_dynamic_query varchar(8000)

    set @my_dynamic_query = 'select [' + @column_name + ']

    INTO ##ResultsTable

    from [' + @table_name + ']

    where [' + @column_name + '] = 23'

    sp_executesql @my_dynamic_query

    select @myVar = columname from ##ResultsTable

    drop ##ResultsTable

    Should work, but it's not the most elegant solution.

    Regards

    JP

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

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