刪除指定表的所有索引,包括主鍵索引,唯一索引和普通索引 ,適用於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
go

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
 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM