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 |
|
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 variableThanks 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. |
 |
|
|
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 ? |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
|
|
|