ITPub博客

首页 > 数据库 > 数据库开发技术 > 删除SQL表数据时存在约束的解决方法!

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

原创 数据库开发技术 作者:deaming317 时间:2020-03-24 21:54:02 0 删除 编辑






这几天在做项目时,清除库中的数据,但是各表之间都存在约束关系,无法使用 ‘ 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';


(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 tablenameADD CONSTRAINT DF_tablename_列名 DEFAULT(0) FOR 列名

--添加范围约束

alter table  tablename  add  check(性别 in ('M','F'))
感觉不错的话,麻烦动动小手关注一下小编啦

更多精彩请点击

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

2.这几个 IntelliJ IDEA 高级调试技巧,用了都说爽!

3.GIT常用命令清单

4.如何快速的创建一个 SpringBoot 项目?

原文作者:程序员Style;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-03-04

  • 博文量
    119
  • 访问量
    52229