sql 2005/ sql 2008
Declare @temp nvarchar(1000)
set @temp = 'ABC'
select col1,col2 from tableA
Along with select query, how to add a variable to the select query ?
expected output :-
select col1,col2,@temp as [col3] from tableA
Where @temp specifies the name of a column in tableA.
If you are trying to specify the column name dynamically, you could take a look at executing dynamic sql. However, you should make sure to read about the dangers of this approach first:
http://www.sommarskog.se/dynamic_sql.html
From that page, there is a sample that shows dynamically specifying the table name — you could change it so it dynamically specifies the column name instead:
So for example if you had a table ‘MyTable’ with columns named ‘x’, ‘y’, and ‘z’, it might look like: