Oracle临时表攻略    

PL/SQL编程武器库 临时表

环境准备

建立两种临时表 ,本例使用scott用户下的emp表中的数据作为临时表数据

--建立两张临时表

--建立事务级临时表

create

global

temporary table emp_delete on commit delete rows

as select *

from emp

where 1=2

--建立会话级临时表

create

global

temporary table emp_preserve on commit preserve rows

as select *

from emp

where 1=2

下面说一下两种临时表的异同

相同点:两种表都不能永久的保存记录。他们都是用临时表空间。

不同点:事务级临时表临时表在提交后就回被清空。

而会话级临时表只有在SESSION 断开后才会被清空。

临时表的使用范围:

建议:在逻辑相当复杂,并且生成的数据

实验步骤如下

向事务级表插入数据

insert into EMP_DELETE

select * from emp

不提交而是在同一个回话中查询这个表的数据

select * from EMP_DELETE 这时候是有数据的。

确认提交

再次查询临时表的数据。

select * from EMP_DELETE

这个时候是没有数据的。在提交的时候,是事务级临时表已经被清空了。

再对会话级临时表做相同的动作。插入数据

insert into EMP_PRESERVE

select * from emp

查询

select *

from EMP_PRESERVE

确认提交

再次查询

select *

from EMP_PRESERVE

仍然有数据。

但是在别的session中却查询不出数据。

select *

from EMP_PRESERVE

当我们关闭这个session的窗口时,数据就被清空了。

当我们使用union 将多个结果集区分的时候,可以使用with构建一张虚拟的临时表

With fis as (select * from emp)

select *

from fis

where empno <7900

union

PL/SQL编程武器库 临时表

环境准备

建立两种临时表 ,本例使用scott用户下的emp表中的数据作为临时表数据

--建立两张临时表

--建立事务级临时表

create

global

temporary table emp_delete on commit delete rows

as select *

from emp

where 1=2

--建立会话级临时表

create

global

temporary table emp_preserve on commit preserve rows

as select *

from emp

where 1=2

下面说一下两种临时表的异同

相同点:两种表都不能永久的保存记录。他们都是用临时表空间。

不同点:事务级临时表临时表在提交后就回被清空。

而会话级临时表只有在SESSION 断开后才会被清空。

临时表的使用范围:

建议:在逻辑相当复杂,并且生成的数据

实验步骤如下

向事务级表插入数据

insert into EMP_DELETE

select * from emp

不提交而是在同一个回话中查询这个表的数据

select * from EMP_DELETE 这时候是有数据的。

确认提交

再次查询临时表的数据。

select * from EMP_DELETE

这个时候是没有数据的。在提交的时候,是事务级临时表已经被清空了。

再对会话级临时表做相同的动作。插入数据

insert into EMP_PRESERVE

select * from emp

查询

select *

from EMP_PRESERVE

确认提交

再次查询

select *

from EMP_PRESERVE

仍然有数据。

但是在别的session中却查询不出数据。

select *

from EMP_PRESERVE

当我们关闭这个session的窗口时,数据就被清空了。

当我们使用union 将多个结果集区分的时候,可以使用with构建一张虚拟的临时表

With fis as (select * from emp)

select *

from fis

where empno <7900

union

select *

from fis

where deptno=20

使用它你不用再建立临时表。

但是With 只能在select 中使用,并且只对一条语句使用。

select *

from fis

where deptno=20

使用它你不用再建立临时表。

但是With 只能在select 中使用,并且只对一条语句使用。

关联文档