当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL server查看各表的索引(sql语句大全)

SQL server查看各表的索引(sql语句大全)

2024年05月18日 MsSqlserver 我要评论
1、要查看 sql server 数据库中的索引,可以使用如下 sql 语句:select tablename = t.name, indexname = ind.name, ind

1、要查看 sql server 数据库中的索引,可以使用如下 sql 语句:

select
    tablename = t.name,
    indexname = ind.name,
    ind.type_desc,
    ind.is_unique,
    ind.is_primary_key,
    columnnames =
        stuff(
            (
                select ', ' + col.name +
                case when ic.is_descending_key = 1 then ' desc' else '' end
                from sys.index_columns ic
                    inner join sys.columns col on ic.object_id = col.object_id and ic.column_id = col.column_id
                where
                    ic.object_id = ind.object_id
                    and ic.index_id = ind.index_id
                order by
                    ic.index_column_id
                for xml path ('')
            ),1,2,''
        )
from
    sys.indexes ind
    inner join sys.tables t on ind.object_id = t.object_id
    inner join sys.schemas s on t.schema_id = s.schema_id
where
    ind.name is not null
order by
    t.name, ind.name;

这条 sql 语句查询了系统元数据表,包含了以下信息:

- 表名

- 索引名

- 索引类型(聚集索引或非聚集索引)

- 是否是唯一索引

- 是否是主键索引

- 索引包含的列名

执行上述 sql 语句,将返回数据库中所有表的所有索引,并列出了每个索引的详细信息,包括列名、类型、是否唯一和主键等信息。可以根据这些信息来进行索引的优化和调整,以提高查询性能。

2、要查看 sql server 数据库中指定的多个表上的索引,可以使用如下 sql 语句:

select
    tablename = t.name,
    indexname = ind.name,
    ind.type_desc,
    ind.is_unique,
    ind.is_primary_key,
    columnnames =
        stuff(
            (
                select ', ' + col.name +
                case when ic.is_descending_key = 1 then ' desc' else '' end
                from sys.index_columns ic
                    inner join sys.columns col on ic.object_id = col.object_id and ic.column_id = col.column_id
                where
                    ic.object_id = ind.object_id
                    and ic.index_id = ind.index_id
                order by
                    ic.index_column_id
                for xml path ('')
            ),1,2,''
        )
from
    sys.indexes ind
    inner join sys.tables t on ind.object_id = t.object_id
    inner join sys.schemas s on t.schema_id = s.schema_id
where
    t.name in ('table1', 'table2', 'table3') -- 替换成你要查询的多个表名,用逗号分隔
order by
    t.name, ind.name;

将上述 sql 语句中的 `in ('table1', 'table2', 'table3')` 替换为你要查询的多个表名,并根据需要修改其他查询条件。执行该 sql 语句将返回指定表上的所有索引,并列出每个索引的详细信息,包括索引名、类型、是否唯一和主键等信息。

注意:确保将表名作为字符串按正确的语法提供给 `in` 表达式,并在 sql 查询中使用正确的数据库上下文。

到此这篇关于sql server查看各表的索引的文章就介绍到这了,更多相关sql server索引内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com