SQL - 仅查询该表中的前25列

时间:2011-09-21 21:17:25

标签: sql sql-server tsql sql-server-2008

表中的75列 - 我想只查询该表中的前25列而不命名每个列名....你可以帮助SQL查询....

我一直在玩以下内容:

Select Table_Name, Count(*) As ColumnCount
From   Information_Schema.Columns
Group By Table_Name
Order By Table_Name

不符合我的输出........

如果表有75列,如何在不命名每个列名的情况下查看前25列?不想删除列只想在同一个表中看到75列中的前25列..... TOP不启用需要另外的工作....

2 个答案:

答案 0 :(得分:4)

表查询中的前25列内置到@query中然后执行。替换正确的@target_table值。

DECLARE
    @target_table sysname
,   @query nvarchar(max)

SET
    @target_table = '_dimAreaOverlay'

; with of_interest as
(
SELECT
    SS.name AS schemaname
,   T.name AS tablename
,   SC.name AS columname
FROM
    sys.schemas SS
    inner join
        sys.tables T
        ON T.schema_id = SS.schema_id
    inner join
        sys.columns SC
        ON SC.object_id = T.object_id
WHERE
    T.name = @target_table
    AND SC.column_id < 26
)
, c AS
(
    SELECT 
        STUFF((
        SELECT 
            ',' + QUOTENAME(I.columname)
        FROM
            of_interest I
        FOR XML PATH('')), 1,1, '') AS column_list
    ,   OI.tablename
    ,   OI.schemaname
    FROM
        of_interest OI
    GROUP BY
        OI.schemaname
    ,    OI.tablename
)
SELECT
    @query = 'SELECT ' 
    + C.column_list 
    + ' FROM ' 
    + QUOTENAME(C.schemaname) 
    + '.' 
    + QUOTENAME(C.tablename)
FROM C

EXECUTE(@query)

答案 1 :(得分:3)

  1. 在Management Studio对象资源管理器中查找该表。
  2. 右键单击它并选择Script Table As -> Select To -> New Query Editor Window
  3. 删除不需要的列。