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
 SQL Server Development (2000)
 Dynamic field select - code posted

Author  Topic 

purell
Starting Member

17 Posts

Posted - 2007-03-15 : 15:10:57
declare @requestfield varchar(100)
Select @requestfield = Column_name from information_Schema.columns
where column_name like 'Reason%' and table_name like 'test'

--this makes @requestfield = reason_for_field

select @requestfield from test

There is a field called reason_for_field in the test table. which has values. But when i run select @requestfield from test - i only get back "reason_for_field". It doesn't understand it's a field in the db. It's thinking it's a string.

How do i solve this?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-03-15 : 15:13:00
exec ('select ' + @requestfield + ' from test')

Be warned though that this is bad from a security and performance perspective.

Tara Kizer
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

purell
Starting Member

17 Posts

Posted - 2007-03-15 : 15:18:21
ah ya - i wanted to avoid that. i'll end up doing this on .net instead of a sp.
Go to Top of Page
   

- Advertisement -