Vishal Seth
Vishal Seth

Reputation: 5048

Is there a way to select nth column in a SELECT clause from a table/view

I've this GIGANTIC view with several hundred columns and I need to select 114th column something like:

SELECT "144" FROM MyView;

PS: Obviously, I don't know the name of the column. I just copied the results row into an Excel file, searched for a particular value that is in EJ column so I want to select all rows showing only nth column in my view to do my further debugging.

Cheers!

Upvotes: 6

Views: 22156

Answers (5)

ruud szwajcer
ruud szwajcer

Reputation: 11

I was having the same problem and solved it by this code. Use this in Stored procedure

DECLARE @TableName as nVarchar(100);
DECLARE @NthColumn as Int

--we are fetching 1st column here.

SELECT 

@TableName =N'YOURTABLE',
@NthColumn=1 --Change if necessary

DECLARE @ColumnName as varchar(100);
SELECT @ColumnName = Col_name(object_id(@TableName),@NthColumn); 

EXEC ('SELECT ' + @ColumnName + ' FROM ' + @TableName);

Upvotes: 1

Ben.Vineyard
Ben.Vineyard

Reputation: 1169

You could use the following in a generic stored procedure, where you pass in the column name, table name, and the value of n. This will work on MSSQL 2000 - 2008.

CREATE PROC usp_select_Nth 
(
    @table_name sysname,
    @column_name sysname,
    @nth int
)
AS
BEGIN

SET @exec = 'SELECT MAX(' + @column_name + ') from ' + @table_name + ' WHERE ' + @column_name + ' NOT IN ( SELECT TOP ' + LTRIM(STR(@nth - 1)) + ' ' + @column_name + ' FROM ' + @table_name + ' ORDER BY ' + @column_name + ' DESC )'
EXEC (@exec)

END

Upvotes: 2

cfeduke
cfeduke

Reputation: 23236

If you are using MS SQL Server you can

sp_help ViewName

and then scroll to the 144th column in the Column_name result set to see what the name of that column is.

Additionally you can choose "Copy with Headers" in the result pane in SQL Server Management Studio and paste the result set into Excel with the headers (column names) intact.

Upvotes: 2

MindStalker
MindStalker

Reputation: 14864

I'd suggest giving all the columns names based upon their Excel column name. There should be an excel solution to make the first row equal to the column name (ie AA, BB, etc). Then do your import, then select based upon the column name which should be computable.

Upvotes: 2

Dolph
Dolph

Reputation: 50720

No, you can't select by index using either standard SQL or Oracle.

Other databases vendors may have their own proprietary command for doing this, however.

Upvotes: 0

Related Questions