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)
 Using variable for select statement

Author  Topic 

jorgen
Starting Member

3 Posts

Posted - 2007-06-26 : 06:30:48

Hi everyone.

How do I use a variable to pass a column name for SELECT statement ?

I tried:




DECLARE

@vari VARCHAR(100)


set @vari=(SELECT distinct(SELECT COL_NAME(OBJECT_ID('test1'), 1)) from test1)

select CAST(@vari as varchar(100)) from test1



... but it returns column name instead of values.

Notice: test1 is a name of a table I retrieve column name from and then pass it to variable


Thanks for all suggestions.

nr
SQLTeam MVY

12543 Posts

Posted - 2007-06-26 : 06:46:09
exec ('select ' + @colname + ' from tbl where x = ''x''')

Can't be bothered to say why this is a bad idea but someone will post links for you.
Do a search for dynamic sql.


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

jorgen
Starting Member

3 Posts

Posted - 2007-06-26 : 07:02:49
quote:
Originally posted by nr

exec ('select ' + @colname + ' from tbl where x = ''x''')

Can't be bothered to say why this is a bad idea but someone will post links for you.
Do a search for dynamic sql.




Thanks for your quick reply, but how do I assign the result (using OUTPUT ?) to a variable ?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-06-26 : 08:36:59
Make sure you read this fully
http://www.sommarskog.se/dynamic_sql.html


Madhivanan

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

- Advertisement -