Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
nmarks
Yak Posting Veteran
53 Posts |
Posted - 2007-11-07 : 06:57:58
|
| I need to refer to columns in a table conditionally. Can I store a column name in a variable an refer to it in an SQL statement?For instance:IF @choice = 1 BEGIN SET @column_name = 'red' ENDELSE BEGIN SET @column_name = 'blue' ENDSELECT @column_name FROM my_tableSomething like this functionality would be very helpful if passing parameters to function calls. |
|
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2007-11-07 : 07:01:58
|
| Can you show us what is the query that you are trying to write? May be CASE statement can help you.Harsh AthalyeIndia."The IMPOSSIBLE is often UNTRIED" |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2007-11-07 : 07:44:32
|
| Select col from(Select red as col,1 as column_choice from tableunion allSelect blue,2 as column_choice from table) as twhere column_choice=@your_choiceMadhivananFailing to plan is Planning to fail |
 |
|
|
nmarks
Yak Posting Veteran
53 Posts |
Posted - 2007-11-07 : 08:12:06
|
| harsh_athalye : the problem has gone away anyway but thanks for offering to help.Madhivanan : the instance given was just a simple example to explain the principle of the problem. Unfortunately your answer doesn't address that principle but thanks for having a try. The point of my original question was : Can you put a variable in a SELECT statement to use as a proxy for a column name, such as 'SELECT @column_name FROM my_table'.Most people would rather die than think; in fact they do so.(Bertrand Russell) |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2007-11-07 : 08:14:13
|
| Yes with the help of dynamic sqlBut it is better not to pass object names as parameterwww.sommarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|