日期:2014-05-16  浏览次数:20396 次

如何查找索引对应字段

首先了解一下sql server系统表:
sys.indexes 索引
sys.objects 对象(表...)
sys.columns 字段
sys.index_columns 索引_字段
sys.tables 自定义表
【具体信息不多解释】

?

已知有employeeinfo表,字段名为userid是唯一键(索引名为IX_employeeinfo)
问题1,如何查找索引对应字段?
select * from sys.columns where column_id in(
select column_id from sys.index_columns where index_id in(
select index_id from sys.indexes where object_id in(
select object_id from sys.tables where name='employeeinfo'
) and name='IX_employeeinfo'
) and object_id=object_id('employeeinfo')
) and object_id=object_id('employeeinfo')

反过来,如何查找字段对应索引?
select * from sys.indexes where index_id in(
select index_id from sys.index_columns where column_id in(
select column_id from sys.columns where object_id in(
select object_id from sys.tables where name='employeeinfo'
) and name='userid'
) and object_id=object_id('employeeinfo')
) and object_id=object_id('employeeinfo')


注:
object_id('employeeinfo')--获取对象id