如何在oracle中创建临时表而不知道列的数量和名称。
例如:
从tableA中选择columnA,columnB,* into temp_table。这里,tableA可能不是一个简单的表名…
在Oracle中,您必须先创建一个表,然后插入其中。或者,直接创建它(如我的例子)。
请注意,我创建了一个“普通”表;如果是的话 临时 ,你可以在a之间选择 全球 要么 私人的 (取决于您使用的数据库版本)。
对于这个讨论,我想这很好:
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>
我不确定为什么你想要一个临时表,因为你不知道列,但你可以考虑动态SQL来创建表,具体取决于你的过程中所需的列,然后再次删除它。从我的角度来看,我认为这不是一个好的设计。
我建议考虑使用带有'x'列数的集合,数据类型为VARCHAR2。在交易期间,您可以根据需要进行填充和处理,它也将保留在该会话中。
这个陈述创造了 temp_table 其中包含来自的所有列和数据 tableA 和另外两个空列varchar和numeric。
temp_table
tableA
create table temp_table as select cast (null as varchar2(10)) columnA, cast (null as number(6)) columnB, tableA.* from tableA
如果您只需要结构,没有数据,那么添加:
where 1 = 0