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 2000 Forums
 Transact-SQL (2000)
 select variable column from table

Author  Topic 

u2p_inst
Yak Posting Veteran

78 Posts

Posted - 2003-09-11 : 04:27:58
i have field in a table like this:
Col_01,Col_02,Col_03
and i have query like this :
Declare @Var1 as varchar(2)
Set @Var1 = '02'
select 'Col_'+@Var1 from table1
and the result
Col_02
Col_02
Col_02
but i need the result like if we execute the query like this
"Select Col_02 from table1"

oh

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2003-09-11 : 05:44:20
Try this:

SELECT
CASE @Var1
WHEN '01' THEN Col_01
WHEN '02' THEN Col_02
WHEN '03' THEN Col_03
END AS Result
FROM TableName


Owais




Make it idiot proof and someone will make a better idiot
Go to Top of Page

mr_mist
Grunnio

1870 Posts

Posted - 2003-09-11 : 05:46:12
Someone asked this the other day. You need dynamic SQL. TBH, you should consider why you're having to do this.

Anyway

create table #moo (col01 int, col02 int)
insert into #moo values (1,2)

declare @first varchar (5)
declare @stmt nvarchar (200)

SELECT @first = '02'

SELECT @stmt = N'SELECT ' + @first + ' from #moo'

exec sp_executesql @stmt

drop table #moo



Ignore me. I was thinking of something else entirely.

-------
Moo. :)

Go to Top of Page
   

- Advertisement -