Is there a way to select nth column in a SELECT cl

2019-01-15 17:10发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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


回答4:

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.



回答5:

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);