如何使用现有表的列名创建表?

时间:2015-08-20 06:35:08

标签: oracle stored-procedures dynamic-sql

我有一个包含400列的表x,如xpk,x1,x2..x399(其中xpk是表的主键)。根据要求,我需要为除xpk之外的每列创建一个单独的表。

传统上我要编写400个create语句。你能帮我用程序或动态sql实现这个目的吗?

我在员工桌上尝试过一些东西只是为了给你一个想法。但即便如此,我也会遇到错误。

set serveroutput on;
DECLARE CURSOR COL_CUR IS
    select column_name from all_tab_columns where table_name = 'EMPLOYEES';
    NAMES user_tables.table_name%TYPE;
    SQL_STRING VARCHAR2(300);
BEGIN

    OPEN COL_CUR;
    LOOP
      FETCH COL_CUR INTO NAMES;
      EXIT WHEN COL_CUR%NOTFOUND;
      SQL_STRING := 'CREATE TABLE :T_NAMES AS SELECT employee_id, :C_NAMES FROM EMPLOYEES';
      EXECUTE IMMEDIATE SQL_STRING  USING NAMES,NAMES;
    END LOOP;
    CLOSE COL_CUR;
END;

必需的输出:

First_name作为具有以下列的表:

Employee_id  First_name
1234          Ashish

同样我想要其他列的表。

2 个答案:

答案 0 :(得分:1)

我们不能在动态DDL中使用绑定变量。你需要像这样重写内部代码:

SQL_STRING := 'CREATE TABLE '|| NAMES ||
              ' AS SELECT employee_id, '|| NAMES ||' FROM EMPLOYEES';
EXECUTE IMMEDIATE SQL_STRING;

答案 1 :(得分:0)

set serveroutput on;
DECLARE CURSOR COL_CUR IS
    select column_name from all_tab_columns where table_name = 'EMPLOYEES' and Column_name != 'employee_id';
    NAMES user_tables.table_name%TYPE;
    SQL_STRING VARCHAR2(300);
BEGIN

    OPEN COL_CUR;
    LOOP
      FETCH COL_CUR INTO NAMES;
      EXIT WHEN COL_CUR%NOTFOUND;
      SQL_STRING := 'CREATE TABLE '|| NAMES ||
              ' AS SELECT employee_id, '|| NAMES ||' FROM EMPLOYEES';
      EXECUTE IMMEDIATE SQL_STRING  USING NAMES,NAMES;
    END LOOP;
    CLOSE COL_CUR;
END;