删除指定表的所有索引,包括主键索引,唯一索引和普通索引 ,适用于sql server 2005,

--删除指定表中所有索引
--用法:declare @tableName varchar(100) 
--set @tableName='表名' --表名 ,根据实际情况替换
--exec sp_dropindex @tableName
if exists(select 1 from sysobjects where id = object_id('dropindex') and xtype = 'P') 
drop procedure dropindex 
go

create procedure dropindex @tableName varchar(100)=null --表名
as

if @tableName is null 
begin 
 raiserror('必须提供@tableName参数',12,1) 
 return 
end

create table # ( 
 id int identity, 
 index_name varchar(50), 
 index_description varchar(1000), 
 index_keys varchar(100) 
)

insert #(index_name,index_description,index_keys) 
exec sp_helpindex @tableName

declare @i int
declare @sql varchar(100)
 
set @i = 1

while @i<=(select max(id) from #) 
begin 
 if exists(select 1 from sysobjects A join # B on A.name=B.index_name where B.id=@i and A.xtype in ('PK','UQ')) 
 begin 
  select @sql = 'alter table '+ @tableName +' drop constraint ' + (select index_name from # where id = @i) 
 end 
 else 
 begin 
  select @sql = 'drop index '+ @tableName + '.' + (select index_name from # where id=@i) 
 end 
 
-- print(@sql) 
    exec(@sql) 
 set @i=@i+1 
end

drop table #

go

 

先执行上面的SQL语句,然后再执行此存储过程即可

 

--删除索引
declare @tableName varchar(100) 
set @tableName='table' --表名 ,根据实际情况替换
exec dropindex @tableName
GO

 

posted @ 2014-08-05 16:47  星火卓越  阅读(1416)  评论(0编辑  收藏  举报