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
 General SQL Server Forums
 New to SQL Server Programming
 nth column

Author  Topic 

msvdm
Starting Member

17 Posts

Posted - 2011-09-13 : 16:06:30
How can I select nth column in in a table.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-09-13 : 16:08:09
If you want the name of the column, then use INFORMATION_SCHEMA.COLUMNS.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2011-09-13 : 16:12:29
It's not a good idea to begin with, but you can do it like this
Declare @n int
Declare @table sysname
Declare @col sysname

Set @table = 'YourTable'
Set @n = 3

SELECT @col = name FROM sys.columns WHERE object_id = object_id(@table)

IF @col IS NOT NULL
BEGIN
EXEC ('SELECT [' + @col + '] FROM [' + @table + '];')
END


Go to Top of Page
   

- Advertisement -