删除SQL表数据时存在约束的解决方法

这几天在做项目时,清除库中的数据,但是各表之间都存在约束关系,无法使用 ‘ truncate table 表名 ’语句进行操作,通过查询资料,找到了解决方法,当表之间存在约束关联时,想要执行truncate删除语句,就要先将约束禁用掉,删除后在恢复约束,就可以操作了。具体方法如下:

(1)查询要删除表存在哪些约束的SQL

select constraint_name, constraint_type, status from user_constraints where table_name='要删除的表名';

select constraint_name, constraint_type, status from user_constraints where table_name='PRJ_PROJECT';

删除SQL表数据时存在约束的解决方法_第1张图片

(2)禁止外键约束的SQL

   方式一:
       alter table '表名' disable constraint '约束名称'

       alter table PRJ_PROJECT disable constraint SYS_C0018174;

   方式二:

      alter table '表名' modify constraint '约束名称' disable cascade;

      alter table PRJ_PROJECT modify constraint PK_PRJ_PROJECT disable cascade;

(3)执行truncate 语句删除数据

       truncate table '表名'

       truncate table PRJ_PROJECT;

(4)恢复外键约束的SQL

   方式一:

       alter table '要恢复的表名' enable constraint '约束名称';

       alter table PRJ_PROJECT enable constraint SYS_C0018174; 

   方式二:

       alter table '要恢复的表名' modify constraint '约束名称' enable;

       alter table PRJ_PROJECT modify constraint PK_PRJ_PROJECT enable;


对创建及删除一些表、字段、列及范围的约束的相关操作进行了总结整理,具体如下:

创建与删除SQL约束或字段约束

1)禁止所有表约束的SQL
select 'alter table ' + name + ' nocheck constraint all' from sysobjects where type='U'

2)删除所有表数据的SQL
select 'truncate table ' + name from sysobjects where type='U'

3)恢复所有表约束的SQL
select 'alter table ' + name + ' check constraint all' from sysobjects where type='U'

4)删除某字段的约束
declare @name varchar(100)
--DF为约束名称前缀
select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'
--删除约束
alter table 表名 drop constraint @name
--为字段添加新默认值和约束
ALTER TABLE 表名 ADD CONSTRAINT @name  DEFAULT (0) FOR [字段名]

--删除约束
ALTER TABLE tablename Drop CONSTRAINT 约束名
--修改表中已经存在的列的属性(不包括约束,但可以为主键或递增或唯一)
ALTER TABLE tablename 
alter column 列名 int not null
--添加列的约束
ALTER TABLE tablename
ADD CONSTRAINT DF_tablename_列名 DEFAULT(0) FOR 列名
--添加范围约束
alter table  tablename  add  check(性别 in ('M','F'))

你可能感兴趣的:(SQL)