天天看點

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

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

使用說明 :

1,先執行腳本,将存儲過程建立在資料庫中

2,調用方法,以黃金搭檔資料庫為例

use velcromfm --資料庫名, 根據具體項目替換

go

declare @tableName varchar(20)

set @tableName='menu' --表名 ,根據實際情況替換

exec sp_dropindex @tableName

3,如有需要,該腳本稍加改寫就可以做成一個删除資料庫所有索引的腳本

提供一個思路 :

select * from sysobjects where xtype='u' --查除資料庫裡所有的表,使用遊标周遊執行這個存儲過程

4,該腳本有個問題,如果某個pk索引是另外一個表的外鍵的話就删不掉,但在velcro系統的資料庫不會有這個麻煩,應為我們的系統沒有設任何外鍵^-^

腳本如下

*/

----------------------------- 腳本---------------------------------------------------

if exists(select 1 from sysobjects where id = object_id('sp_dropindex') and xtype = 'P')

drop procedure sp_dropindex

create procedure sp_dropindex @tableName varchar(50)=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

  select @sql = 'alter table '+ @tableName +' drop constraint ' + (select index_name from # where id = @i)

 end

 else

-- print(@sql)

    exec(@sql) 

 set @i=@i+1

drop table #