我找到了这个问题,但它似乎没有回答这个问题...
SQL Server - How to find if clustered index exists
如何编写 IF T-SQL 语句来表示:
IF NOT ([TableName] has a CLUSTERED PK)
ALTER TABLE to add the CLUSTERED PK
最佳答案
试试这个
IF NOT EXISTS (SELECT *
FROM sys.indexes
WHERE object_id = OBJECT_ID('dbo.MdsInventar')
AND index_id = 1
AND is_primary_key = 1)
......
聚集索引始终具有 index_id
= 1。当然 - 如果您像这样检查(使用 is_primary_key = 1
条件),那么总是有可能存在可能已经是表上的非主聚集索引 - 因此您将无法创建另一个聚集索引。因此,也许您需要丢失 AND is_primary_key = 1
条件并仅检查“是否存在聚集索引”。
更新:或者如果使用index_id = 1
对您来说似乎是黑魔法,您也可以使用type
列来代替:
IF NOT EXISTS (SELECT *
FROM sys.indexes
WHERE object_id = OBJECT_ID('dbo.MdsInventar')
AND type = 1
AND is_primary_key = 1)
......
关于sql - 如何查询表是否具有聚集主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21167631/