create proc pdropindex 
@tbname varchar(100)
as begin 
declare @sql varchar(8000)
declare @i int
set @i=1
set @sql=''
select id=identity(int,1,1),name into #1 from sysindexes where id=object_id(@tbname) and indid > 0 and indid < 255 and (status & 64)=0
while @i<=(select max(id) from #1) begin
set @sql=(select 'drop index '+@tbname+'.'+name from #1 where id=@i)
exec  @sql
set @i=@i+1 
end 
end

解决方案 »

  1.   

    --调用
    exec pdropindex 表名
      

  2.   

    declare @tb nvarchar(100),@index nvarchar(100)
    declare cur cursor for
    SELECT distinct object_name(a.id),b.name
    FROM sysindexkeys a,sysindexes b,sysobjects c where a.indid=b.indid and a.id=b.id 
    and a.id=c.id and c.xtype='u' and c.status>0
    open cur
    fetch next from cur into @tb,@index
    while @@fetch_status=0
    begin 
    exec('drop index '+@tb+'.'+@index)
    fetch next from cur into @tb,@index
    end
    close cur
    deallocate cur
      

  3.   

    /*
        删除指定表的所有索引,包括主键索引,唯一索引和普通索引
     
        调用:
        declare @tbName varchar(20)
        set @tbName='A'
        exec sp_dropindex @tbName
    */
    if exists(select 1 from sysobjects where id=object_id('sp_dropindex') and xtype='P')
    drop procedure sp_dropindex
    go
    create procedure sp_dropindex
    @tbName varchar(20)=null   --索引名
    asif @tbName is null
    begin
         raiserror('必须提供@tbName参数',12,1)
         return
    endcreate 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 @tbNamedeclare @i int,@sql varchar(100)
    set @i=1while @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 '+@tbName+' drop constraint '
                           +(select index_name from # where id=@i)
               exec(@sql)
          end
          else
          begin
               select @sql='drop index '+@tbName+'.'
                           +(select index_name from # where id=@i)
               exec(@sql)
          end
     
          set @i=@i+1
    enddrop table #go
      

  4.   

    --说明我上面代码是删除所有用户表的索引
    --查看表索引
    exec sp_helpindex tbname
    --查看当前数据库所有表的索引
    SELECT distinct object_name(a.id),b.name
    FROM sysindexkeys a,sysindexes b,sysobjects c where a.indid=b.indid and a.id=b.id 
    and a.id=c.id and c.xtype='u' and c.status>0