【问题标题】:Find Tables Without Clustered Index but with Primary Keys on a table查找没有聚集索引但在表上具有主键的表
【发布时间】:2013-02-26 14:38:49
【问题描述】:

是否有一个脚本可以查找没有聚集索引但上面有 Sql server 2008 r2 主键的表?请告诉我。

【问题讨论】:

  • 您可以使用元数据方案。

标签: sql-server-2008 tsql


【解决方案1】:

类似这样的:

SELECT
            so.name AS TableName,
            si.name AS IndexName,
            si.type_desc AS IndexType,
            si.is_primary_key
FROM
            sys.indexes si
            JOIN sys.tables so ON si.[object_id] = so.[object_id]
WHERE
            si.type IN (0, 2)
            AND si.is_primary_key=1
ORDER BY
            so.name

【讨论】:

  • 或者更好:从 SQL Server 2005 开始,使用更具体的 sys.tables - 让您不必总是为您的表指定 type = 'U'... ..
  • 好多了!另外:我认为应该是si.type IN (0, 2) - “0”代表“堆”,“2”代表其他非聚集索引。
  • si.name is not null 子句实际上消除了任何 type = 0 的行,只是让你知道:)。堆没有索引名称。
【解决方案2】:
select O.name
from sys.objects as O
  inner join sys.indexes as I1
    on O.object_id = I1.object_id
  inner join sys.indexes as I2
    on O.object_id = I2.object_id
where O.type = 'U' and         -- U = Table (user-defined)
      I1.type = 0 and          -- 0 = Heap
      I2.is_primary_key = 1

sys.objects (Transact-SQL)
sys.indexes (Transact-SQL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 2012-06-03
    • 1970-01-01
    • 2018-06-27
    • 2011-03-27
    • 1970-01-01
    • 2012-01-10
    • 2019-06-24
    相关资源
    最近更新 更多