SELECT columns by column-index NOT by column name!

Declare @WhichOne int;
Declare @Sql varchar(200);
SET @WhichOne = 2;
WITH cte AS
(SELECT name, Row_Number() Over (ORDER BY column_id) AS rn
FROM sys.COLUMNS
WHERE Object_Name(object_id) = 'MyTable')
SELECT @Sql = 'Select ' + QuoteName(name) + ' From MyTable'
FROM cte
WHERE rn = @WhichOne;
Exec(@Sql);

Advertisements

One thought on “SELECT columns by column-index NOT by column name!

  1. This will allow me to bring back 1 column. How do I bring back the first 5 columns of a table with this query?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s