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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Refering to column names

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'
END
ELSE
BEGIN
SET @column_name = 'blue'
END

SELECT @column_name FROM my_table

Something 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 Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

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 table
union all
Select blue,2 as column_choice from table
) as t
where column_choice=@your_choice

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

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)
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-11-07 : 08:14:13
Yes with the help of dynamic sql
But it is better not to pass object names as parameter
www.sommarskog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -