从创建特定索引的表中获取列名

时间:2018-06-27 05:25:18

标签: sql-server

SELECT name 
  FROM sys.COLUMNS 
 WHERE object_id = (
                    SELECT object_id 
                      FROM sys.objects 
                     WHERE name = 'Table_name'
                    ) 
   AND column_id = (
                    SELECT COLUMN_ID 
                      FROM sys.index_columns 
                     WHERE object_id = (
                                        SELECT object_id 
                                          FROM sys.objects 
                                         WHERE name = 'Table_name'
                                        )
                    )

我编写了此查询,可以提供正确的结果,但我认为可以用更准确的方式编写。

有人可以帮我以更紧凑的方式编写此查询吗?

2 个答案:

答案 0 :(得分:2)

“更精细”的方法是使用JOIN而不是相关的子查询(在我的情况下,它不起作用并抛出错误:“子查询返回了多行”):

DECLARE @tableName SYSNAME = N'-your-table-name-here-';

SELECT 
    TableName = t.Name,
    IndexName = ix.Name,
    ColumnName = c.name 
FROM 
    sys.indexes ix
INNER JOIN 
    sys.tables t ON t.object_id = ix.object_id
INNER JOIN 
    sys.index_columns ic ON ic.object_id = t.object_id AND ic.index_id = ix.index_id
INNER JOIN 
    sys.columns c ON c.object_id = t.object_id AND c.column_id = ic.column_id
WHERE 
    t.Name = @tableName

我还倾向于尝试使用sys.tables之类的重点更突出的目录视图,而不是依靠“包罗万象” sys.objects视图

答案 1 :(得分:1)

SELECT col.name, ind.name
FROM sys.columns col
INNER JOIN sys.objects obj ON obj.object_id = col.object_id
INNER JOIN sys.index_columns incol ON incol.COLUMN_ID = col.column_id AND incol.object_id = obj.object_id
INNER JOIN sys.indexes ind on ind.index_id = incol.index_id AND obj.object_id = ind.object_id
WHERE obj.name = 'Table_name'

请尝试上述查询以获取列名。我为sys.indexes表又添加了一个连接,以获取索引名称,以防表中有多个索引。 您可以删除此联接(如果不需要)。 (如下)

SELECT col.name
FROM sys.index_columns incol INNER JOIN sys.columns col INNER JOIN sys.objects obj 
  ON obj.object_id = col.object_id 
  ON incol.COLUMN_ID = col.column_id AND incol.object_id = obj.object_id
WHERE obj.name = 'Table_name'