drop index 学生.姓名索引服务器: 消息 3723,级别 16,状态 5,行 1
不允许对索引 '学生.姓名索引' 显式地使用 DROP INDEX。该索引正用于 UNIQUE KEY 约束的强制执行。"姓名索引”是索引名,(姓名字段的unique索引名,这个不是主键)哪出毛病了?怎么办?谢
不允许对索引 '学生.姓名索引' 显式地使用 DROP INDEX。该索引正用于 UNIQUE KEY 约束的强制执行。"姓名索引”是索引名,(姓名字段的unique索引名,这个不是主键)哪出毛病了?怎么办?谢
select name
from sysobjects
where xtype = 'UQ' and parent_obj = object_id('tablename') --如果只有一个unique 约束,可以直接这样 declare @s varchar(100)
select @s = 'alter table tablename drop ' + name
from sysobjects
where xtype = 'UQ' and parent_obj = object_id('tablename')
exec(@s)
--UNIQUE约束可能是由一个列组成,也可能是由多个列组成,一个列也可能参与了多个UNIQUE约束.
下面的存储过程有以下4种调用方式,分别完成不同的功能:
1.查询表的所有UNIQUE约束
EXEC spFindConstraint '表名'
2.查询指定列的所有UNIQUE约束
EXEC spFindConstraint '表名','列名'
3.删除指定列的所有UNIQUE约束
EXEC spFindConstraint '表名','列名',1
4.删除表的所有UNIQUE约束
EXEC spFindConstraint '表名',NULL,1
if object_id('spFindConstraint') is not null
drop proc spFindConstraint
GO
----创建查找/删除UNIQUE约束的存储过程,参数共3个.
CREATE PROC spFindConstraint
@objname nvarchar(776), /*表名称*/
@colname sysname = NULL, /*列名称*/
@dropunique bit = 0 /*是否删除@colname列有关的UNIQUE约束*/
as
set nocount off
declare @objid int --表ID
,@cnstname sysname --UNIQUE约束名称
,@i int
,@cnstid int
,@keys nvarchar(2126)--联合约束的列名称列表
--创建保存UNIQUE约束信息的临时表
create table #spcnsttab
(
cnst_name sysname collate database_default NOT NULL
,cnst_keys nvarchar(2126) collate database_default NULL
)
select @objid = object_id(@objname)
--声明游标
declare ms_crs_cnst cursor local static for
select id,name from sysobjects where parent_obj = @objid and xtype = 'UQ'
for read only
--打开游标
open ms_crs_cnst
--遍历UNIQUE约束
fetch next from ms_crs_cnst into @cnstid ,@cnstname
while @@fetch_status >= 0
begin
declare @indid smallint
select @indid = indid from sysindexes
where name = object_name(@cnstid) and id = @objid
--格式化UNIQUE约束列信息
declare @thiskey nvarchar(131) -- 128+3
select @keys = index_col(@objname, @indid, 1), @i = 2
select @thiskey = index_col(@objname, @indid, @i)
while (@thiskey is not null)
begin
select @keys = @keys + ',' + @thiskey, @i = @i + 1
select @thiskey = index_col(@objname, @indid, @i)
end
--如果未指定列名,则列出所有的UNIQUE约束
if @colname is null
begin
if @dropunique = 1
--删除UNIQUE约束
EXEC('ALTER TABLE ' + @objname + ' DROP CONSTRAINT ' + @cnstname)
else
--保存UNIQUE约束信息
insert into #spcnsttab (cnst_name,cnst_keys) values (@cnstname,@keys)
end
else
--如果指定的列有UNIQUE约束
if charindex(',' + @colname + ',',',' + @keys + ',') > 0
begin
if @dropunique = 1
--删除UNIQUE约束
EXEC('ALTER TABLE ' + @objname + ' DROP CONSTRAINT ' + @cnstname)
else
--保存UNIQUE约束信息
insert into #spcnsttab (cnst_name,cnst_keys) values (@cnstname,@keys)
end
fetch next from ms_crs_cnst into @cnstid ,@cnstname
end
--关闭游标
close ms_crs_cnst
--释放游标
deallocate ms_crs_cnst
--返回UNIQUE约束信息
if @dropunique = 0
select * from #spcnsttab
GO
alter table 学生
drop constraint 姓名索引
就能成功删除