刪除指定表的所有索引,包括主鍵索引,唯一索引和普通索引 ,適用于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
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
