MS SQL Server 中这个SQL怎么写

来源:百度知道 编辑:UC知道 时间:2024/05/29 08:37:20
知道表名 假设为 table1,写一个SQL要求按下列格式返回数据

下面是返回数据的一个例子

假设table1有两个索引index1和index2,
index1是主键,由字段A和B组成
index2是一个普通索引,由字段X,Y,Z字段构成
则返回的数据应该为
索引名称 序号 字段名称 索引类型
index1 1 A 主键
index1 2 B 主键
index2 1 X 普通索引
index2 2 Y 普通索引
index2 3 Z 普通索引
要在MSSQL 2000下运行的

--哈哈,忘记楼主这件事了.SQL2000几年没有用了,楼主看看是不是这样的结果集.
select object_Name(a.ID) as 表名,a.Name as 索引名,b.keyno as 序号,c.Name as 字段名,case when d.ID is null then N'普通索引' when d.xtype='UQ' then N'唯一索引' when d.xtype='PK' then N'主健索引' end as 索引类型
from sysindexes a
inner join sysindexkeys b on a.ID=b.ID and a.indID=b.indid
inner join syscolumns c on c.ID=b.ID and b.colid=c.colid
left join sysobjects d on d.Name=a.Name and d.parent_obj=C.ID
--where a.ID=object_id('表名')--这里可加条件
order by 表名,索引名,序号

SQL2005以上版本用

with Index1
as
(
select
top 100 percent row_number()over(partition by a.Name order by b.index_id) as ID,object_Name(a.object_id) as TableName,a.Name as IndexName,c.Name as ColName,
description=a.type_desc,a.is_unique,a.is_primary_key,a.is_unique_constraint

from
sys.indexes a
join
sys.index_columns b on a.Object_id=b.Object_id and a.ind