SQL Server:查询中没有应该返回数据的数据

时间:2016-04-01 07:49:09

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

我在SQL Server上运行SQL查询,逻辑上应该返回一些数据,但它不会:

SELECT 
    D.NAME DATABASE_NAME, T.NAME TABLE_NAME, I.NAME INDEX_NAME,
    C.NAME COLUMN_NAME
FROM 
    sys.dm_db_index_physical_stats (NULL, NULL, NULL , NULL, 'LIMITED') AS XXX
INNER JOIN 
    SYS.DATABASES AS D ON D.DATABASE_ID = XXX.DATABASE_ID
INNER JOIN 
    SYS.TABLES AS T ON T.OBJECT_ID = XXX.OBJECT_ID
INNER JOIN 
    SYS.INDEXES AS I ON I.OBJECT_ID = T.OBJECT_ID
INNER JOIN 
    SYS.INDEX_COLUMNS IC ON IC.OBJECT_ID = I.OBJECT_ID
INNER JOIN 
    SYS.COLUMNS AS C ON C.OBJECT_ID = IC.OBJECT_ID
WHERE 
    1=1
ORDER BY 
    D.NAME, T.NAME

仅运行此位会输出大量数据:

SELECT * 
FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL , NULL, 'LIMITED')

那么为什么更复杂的查询不起作用呢?

1 个答案:

答案 0 :(得分:0)

你没有正确地加入......

例如,index_columns有一个object_id(用于表)和一个index_id(用于索引)。请注意,indexid不是全局唯一的,而是仅在该表的上下文中唯一(即object_id),因此当您拉入index_columns时需要在两列上连接。

以下是一个例子:

SELECT 
    TOP 50 
      t.name as tablename, 
      i.name as indexname, 
      c.name as columnname, 
      ic.key_ordinal, ic.is_descending_key
FROM sys.tables t
INNER JOIN sys.indexes i
    ON i.object_id = t.object_id
INNER JOIN sys.columns c
    ON c.object_id = t.object_id
INNER JOIN sys.index_columns ic
    ON ic.object_id = t.object_id
    AND ic.index_id = i.index_id
    AND ic.column_id = c.column_id
ORDER by t.name, i.name, c.name, ic.key_ordinal