在本教程中,您将学习如何使用oracle truncate table
语句更快更有效地从表中删除所有数据(也叫截断表)。
如果要从表中删除所有数据,可以使用不带where
子句的delete
语句,如下所示:
delete from table_name;
对于有少量行记录的表,delete
语句做得很好。 但是,当拥有大量行记录的表时,使用delete
语句删除所有数据效率并不高。
oracle引入了truncate table
语句,用于删除大表中的所有行。
以下说明了oracle truncate table
语句的语法:
truncate table schema_name.table_name
[cascade]
[[ preserve | purge] materialized view log ]]
[[ drop | reuse]] storage ]
默认情况下,要从表中删除所有行,请指定要在truncate table
子句中截断的表的名称:
truncate table table_name;
在这种情况下,因为我们没有明确指定模式名称,所以oracle假定从当前的模式中截断表。
如果表通过外键约束与其他表有关系,则需要使用cascade
子句:
truncate table table_name
cascade;
在这种情况下,truncate table cascade
语句删除table_name
表中的所有行,并递归地截断链中的关联表。
请注意,truncate table cascade
语句需要使用on delete cascade
子句定义的外键约束才能工作。
通过materialized view log
子句,可以指定在表上定义的物化视图日志是否在截断表时被保留或清除。 默认情况下,物化视图日志被保留。
storage
子句允许选择删除或重新使用由截断行和关联索引(如果有的话)释放的存储。 默认情况下,存储被删除。
请注意,要截断表,它必须在您自己的模式中,或者必须具有
drop any table
系统权限。
下面我们来看看使用truncate table
语句来删除表的一些例子。
以下语句创建一个名为customers_copy
的表,并从示例数据库中的customers
表复制数据:
create table customers_copy
as
select
*
from
customers;
要从customers_copy
表中删除所有行,请使用以下truncate table
语句:
truncate table customers_copy;
首先,创建用来演示的两个表:quotations
和quotation_items
表:
create table quotations (
quotation_no numeric generated by default as identity,
customer_id numeric not null,
valid_from date not null,
valid_to date not null,
primary key(quotation_no)
);
create table quotation_items (
quotation_no numeric,
item_no numeric ,
product_id numeric not null,
qty numeric not null,
price numeric(9 , 2 ) not null,
primary key (quotation_no , item_no),
constraint fk_quotation foreign key (quotation_no)
references quotations
on delete cascade
);
接下来,在这两个表中插入一些行:
insert into quotations(customer_id, valid_from, valid_to)
values(100, date '2017-09-01', date '2017-12-01');
insert into quotation_items(quotation_no, item_no, product_id, qty, price)
values(1,1,1001,10,90.5);
insert into quotation_items(quotation_no, item_no, product_id, qty, price)
values(1,2,1002,20,200.5);
insert into quotation_items(quotation_no, item_no, product_id, qty, price)
values(1,3,1003,30, 150.5);
然后,截断quotatios
表:
truncate table quotations;
执行语句失败,oracle返回以下错误:
sql error: ora-02266: unique/primary keys in table referenced by enabled foreign keys
要解决这个问题,可以将cascade
子句添加到上面的truncate table
语句中:
truncate table quotations cascade;
这个语句不仅从quotations
表中删除数据,而且还从quotation_items
表中删除数据。最后,验证是否删除了quotations
和quotation_items
中的数据:
select
*
from
quotations;
select
*
from
quotation_items;
请注意,如果没有为
fk_quotation
约束指定on delete cascade
,则上面的truncate table cascade
语句将失败。
在本教程中,我们学习了如何使用oracle truncate table
语句更快更有效地从表中删除所有数据。