开发者

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

I've this GIGANTIC view with sev开发者_Go百科eral 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!


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.


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜