查询使用sql

时间:2017-11-20 16:35:28

标签: sql sql-server tsql unique-index

使用sql查询从数据库中的所有表中提取所有唯一索引。输出应显示模式名称,表名称和列名称。

我尝试了以下查询:

SELECT
     t.[name] AS TableName
    ,i.[name] AS IndexName
    ,c.[name] AS ColumnName
FROM sys.schemas s
INNER JOIN sys.tables t ON t.schema_id = s.schema_id
    AND s.[name] = 'dbo'
INNER JOIN sys.columns c ON c.object_id = t.object_id
INNER JOIN sys.indexes i ON i.object_id = t.object_id
    AND i.index_id > 0
    AND i.is_primary_key = 0
    AND i.is_unique = 1
INNER JOIN sys.index_columns ic ON ic.object_id = t.object_id
    AND ic.column_id = c.column_id

但如果它们有多个唯一索引列,则会多次显示TableNameIndexName

想要显示:

TableName   IndexName           ColumnName
Customers   IX_customer_name    FirstName, LastName

1 个答案:

答案 0 :(得分:0)

您可以使用sp_MSforEachDB存储过程:

EXECUTE master.sys.sp_MSforeachdb '
USE [?];
select db_name(), *
from sys.indexes
where is_unique = 1';

您还可以通过添加if db_id() > 4 begin end来排除系统数据库。