生成索引的语句

来源:互联网 发布:玩游戏学编程app 编辑:程序博客网 时间:2024/05/16 19:50


select d.name
,c.name 
,a.name
,a.[type_desc]  ,
(case
when a.is_primary_key=1
 then
'
ALTER TABLE '+quotename(d.name)+'.'+quotename(c.name)+' ADD  CONSTRAINT '+quotename(a.name)+' PRIMARY KEY '+a.[type_desc]+'
(
'+
stuff(
(
select ','+t2.name+' '+(case when t1.is_descending_key=1 then 'DESC' else 'ASC' end) from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal>0
  order by t1.index_column_id
for xml path('')

),1,1,'')
+'
)
' collate   Chinese_PRC_CI_AI_WS
when a.is_unique=1
 then
'
ALTER TABLE '+quotename(d.name)+'.'+quotename(c.name)+' ADD  CONSTRAINT '+quotename(a.name)+' UNIQUE '+
convert(varchar,a.[type_desc])+'
(
'+
stuff(
(
select ','+t2.name+' '+(case when t1.is_descending_key=1 then 'DESC' else 'ASC' end) from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal>0
  order by t1.index_column_id
for xml path('')

),1,1,'')
+'
)

'
+
(case when exists
(select 1 from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal=0)
 then 'INCLUDE('+
stuff(
(
select ','+t2.name from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal=0
 order by t1.index_column_id
for xml path('')

),1,1,'')+')'
else '' end)
 collate   Chinese_PRC_CI_AI_WS
else 
'
CREATE '+a.[type_desc]+' INDEX '+quotename(a.name)+' ON '+quotename(d.name)+'.'+quotename(c.name)+'
(
'+
stuff(
(
select ','+t2.name+' '+(case when t1.is_descending_key=1 then 'DESC' else 'ASC' end) from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal>0
 order by t1.index_column_id
for xml path('')

),1,1,'')
+'
)
'
+
(case when exists
(select 1 from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal=0)
 then 'INCLUDE('+
stuff(
(
select ','+t2.name from sys.index_columns t1
 inner join sys.all_columns t2 on t1.object_id=a.object_id and t1.index_id=a.index_id
 and t1.object_id=t2.object_id and t1.column_id=t2.column_id and t1.key_ordinal=0
 order by t1.index_column_id
for xml path('')

),1,1,'')+')'
else '' end)
 collate   Chinese_PRC_CI_AI_WS
end)    
,a.* from sys.indexes a
inner join sys.all_objects c on a.object_id=c.object_id and c.type='u'
inner join sys.schemas d on c.schema_id=d.schema_id and a.type_desc in ('CLUSTERED','NONCLUSTERED')