Is there a way to select last N columns in SQL Server Results Tab?

徘徊边缘 提交于 2019-12-11 04:06:04

问题


Shortly,

I don't mean the last 5 rows. via SELECT TOP 5 * FROM Table Order By Key DESC

But I mean last 5 columns in Results Tab.

Why? because each time I add a new column and filling it outside SQL-Server, I need to see its result without moving Horizontal Scroll. and many columns have the same name at the beginning.

It's not coding issues. but it's about the SQL-Server IDE Results tab itself.

I Searched many times. but this thing never asked I think. so please I want an approach for that. I assume something like built-in function or something anyone knows


回答1:


Like I mentioned in the comments, if your table's definition is constantly changing this suggests a far larger design flaw in your database. Object definitions should be pretty static, and they should definitely not be changing every time you connect to the instance. That is the root cause of your problem, not that it's "too difficult", to type the name of 5 columns, rather than using *.

This means fixing your design, which we can't comment on, but I suggest that is your next major step to do. Normalise your design, and use multiple tables (as I suspect you're adding extra columns each time due to a lack of normalisation).

In the interim, you can use dynamic SQL:

DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

DECLARE @Schema sysname = N'dbo',
        @Table sysname = N'rCTE_Vs_Tally';

SET @SQL = N'SELECT ' +
           STUFF((SELECT TOP(5)
                         N',' + @CRLF + 
                         N'       ' + QUOTENAME(c.[name])
                  FROM sys.schemas s
                       JOIN sys.tables t ON s.schema_id = t.schema_id
                       JOIN sys.columns c ON t.object_id = c.object_id
                  WHERE s.[name] = @Schema
                    AND t.[name] = @Table
                  ORDER BY C.column_id DESC
                  FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,10,'') + @CRLF + 
          N'FROM ' + QUOTENAME(@Schema) + N'.' + QUOTENAME(@Table) + @CRLF + 
          N'ORDER BY [Key] DESC;' --Assumes all tables have the column Key
PRINT @SQL;


EXEC sp_executesql @SQL;



回答2:


Probably a dynamic statement, based on system catalog views, may help here:

DECLARE @tablename sysname = 'table'
DECLARE @schemaname sysname = 'dbo'
DECLARE @stm nvarchar(max) 

SELECT @stm = (
    SELECT TOP(5) CONCAT(@stm, N',', col.[name])
    FROM sys.columns col
    JOIN sys.tables tab ON col.object_id = tab.object_id
    JOIN sys.schemas sch ON tab.schema_id = sch.schema_id
    WHERE 
        tab.[name] = @tablename AND 
        sch.[name] = @schemaname
    ORDER BY col.column_id DESC
    FOR XML PATH('')
)
SELECT @stm = CONCAT(
    N'SELECT ',
    STUFF(@stm, 1, 1, N''),
    N' FROM ',
    QUOTENAME(@schemaname),
    N'.',
    QUOTENAME(@tablename)
)

PRINT @stm
EXEC sp_executesql @stm



回答3:


Ok Deveton, as explained, a Dynamic SQL is needed for this.

I think the below would answer your question:

declare @columns    varchar(max)
,       @sql        varchar(max)
,       @tblname    varchar(20)     =   'Settings'

select @columns = stuff((select top 5 ',' + quotename(column_name)
            from information_schema.columns
            where table_name = @tblname
            order by ordinal_position desc
            for xml path(''), type).value('.', 'nvarchar(max)'),1,1,'')

set @sql = 'select '+@columns+' from '+quotename(@tblname)
exec (@sql)

Please advise if it works for you?

EDIT

I also added the functionality to specify top 200 and order by the Identity column descending:

declare @columns    varchar(max)
,       @sql        varchar(max)
,       @tblname    varchar(20)     =   '_btblInvoiceLines'

declare @idcolumn   varchar(max)    =   quotename((select column_name from information_schema.columns where table_name = @tblname and COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1))

select @columns = stuff((select top 5 ',' + quotename(column_name)
            from information_schema.columns
            where table_name = @tblname
            order by ordinal_position desc
            for xml path(''), type).value('.', 'nvarchar(max)'),1,1,'')

set @sql = 'select top 200'+@columns+' from '+quotename(@tblname)+' order by '+@idcolumn+' desc'
print(@sql)
exec (@sql)



回答4:


Just press "End" key when you are in the Results tab. After that you will be at end of columns.



来源:https://stackoverflow.com/questions/59088118/is-there-a-way-to-select-last-n-columns-in-sql-server-results-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!