在不知道Oracle中的列的情况下创建临时表

时间:2019-03-14 10:11:17

标签: oracle plsql temp-tables

如何在不知道列数和名称的情况下在oracle中创建临时表。

例如:

Select columnA,columnB,* into temp_table from tableA.

在这里,tableA可能不是简单的表名,而是可能源自许多查询。

如何实现?还有其他替代方法吗?

3 个答案:

答案 0 :(得分:1)

在Oracle中,您必须首先创建一个表,然后将其插入其中。或者,直接创建它(如我的示例)。

请注意,我已经创建了一个“普通”表;如果是临时,则可以在 global private 之间进行选择(取决于您使用的数据库版本)。

对于这个讨论,我想这很好:

SQL> create table temp_table as
  2    select a.*
  3    from (select d.deptno, d.dname, e.ename    --> this SELECT is your "tableA"
  4          from emp e join dept d
  5          on e.deptno = d.deptno
  6          where job = 'CLERK'
  7         ) a;

Table created.

SQL> select * from temp_table;

    DEPTNO DNAME                ENAME
---------- -------------------- ----------
        10 ACCOUNTING           MILLER
        20 RESEARCH             SMITH
        20 RESEARCH             ADAMS
        30 SALES                JAMES

SQL>

或者,创建一个视图并使用它:

SQL> create or replace view v_temp as
  2          select d.deptno, d.dname, e.ename
  3          from emp e join dept d
  4          on e.deptno = d.deptno
  5          where job = 'CLERK'
  6  ;

View created.

SQL> select * from v_temp;

    DEPTNO DNAME                ENAME
---------- -------------------- ----------
        10 ACCOUNTING           MILLER
        20 RESEARCH             SMITH
        20 RESEARCH             ADAMS
        30 SALES                JAMES

SQL>

答案 1 :(得分:1)

此语句创建temp_table,其中包含tableA中的所有列和数据以及另外两个空列varchar和numeric。

create table temp_table as 
  select cast (null as varchar2(10)) columnA, 
         cast (null as number(6)) columnB, 
         tableA.* 
    from tableA

如果只需要结构,不需要数据,则添加:

    where 1 = 0

答案 2 :(得分:0)

我不确定您为什么要拥有一个临时表,因为您不知道列,但是您可以考虑使用动态SQL根据过程中所需的列来创建表,然后将其再次删除。从我的角度来看,我认为这不是一个好的设计。

我建议考虑使用数据类型为VARCHAR2的'x'列数的collection。在交易过程中,您可以根据需要进行填充和处理,并且在该会话中也将保留。

相关问题