Search code examples
sql-servert-sqlvariablesreusability

Reusing column name as declared variable in SQL select statement


I am working on one project in which column names get changed in every month. So I am trying to declare a variable which contains the column names which I can reuse. So I did this.

declare @cal_name varchar(max) = 'ID'
select @cal_name from Table_A
union all
select @cal_name from Table_B

But this just print the ID as a string in result box. I don't want to use another variable to store sql statement, can anyone help me to make query as per my requirement.


Solution

  • Something like this?

    declare @cal_name varchar(max) = 'ID'    
    exec
    (
        'select ' + @cal_name + ' from Table_A
        union all
        select ' + @cal_name + ' from Table_B'
    )