在不知道 oracle 中的列的情况下创建临时 table

Creating temporary table without knowing the columns in oracle

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

例如:

Select columnA,columnB,* into temp_table from tableA.

这里,tableA 可能不是一个简单的table名称,但可能来自许多查询。

如何实现?有什么替代方案吗?

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

请注意,我创建了一个 "normal" table;如果它是 temporary,您可以在 globalprivate 之间进行选择(取决于您使用的数据库版本使用).

对于这个讨论,我觉得还可以:

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>

我不确定你为什么想要一个临时 table 因为你不知道列,但你可以考虑动态 SQL 来创建 table 取决于所需的列在你的过程中,然后再次放下它。从我的角度来看,我认为这不是一个好的设计。

我可以建议考虑使用具有 'x' 列数且数据类型为 VARCHAR2 的集合。在交易期间,您可以根据需要填充和处理,它也将保留该会话。

此语句创建 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