如何在嵌套的pl / sql块中立即创建表

时间:2015-07-30 14:55:26

标签: sql oracle nested block

我正在创建表,然后将这些表的计数存储在变量中,所有这些都在Oracle数据库的嵌套pl / sql块中。我收到错误“ORA-00942:表或视图不存在”。如果我先创建表,然后运行我的块,它执行没有错误。

因此,我知道即使我使用EXECUTE IMMEDIATE命令也没有创建表。 (我认为这个命令会绕过PL / SQL块中使用的所有对象必须在执行PL / SQL块之前存在的事实。)

此时很难在我的块之外创建表,还有另一种方法吗?

以下示例代码:

DECLARE
  g_user varchar2(30) := 'schema';
BEGIN
  /* more code and nested blocks*/
  DECLARE
    v_Count_Task1A number(6);
  BEGIN

    EXECUTE IMMEDIATE 'CREATE TABLE ' ||g_user||'.T_Task1A_Roles_w_User_IDs  AS
    SELECT ROWNUM AS Dummy_Field, USUS_ID AS Task1A_Role, User_ID AS Task1A_User_ID
    FROM Task1A_Roles_w_User_IDs';

    SELECT count(1) INTO v_Count_Task1A
    FROM T_Task1A_Roles_w_User_IDs;
    /*more operations like this*/
  END;
  /* more code and nested blocks*/
END;

2 个答案:

答案 0 :(得分:3)

问题不是当块运行时你的表没有被创建,问题是当编译PL / SQL时表不存在,所以它可以&#39 ;编译,因此根本无法运行。

这里的解决方案是使用更多动态SQL来执行计数,因为在执行块之前不会解析动态SQL:

DECLARE
  g_user varchar2(30) := 'schema';
BEGIN
  /* more code and nested blocks*/
  DECLARE
    v_Count_Task1A number(6);
  BEGIN

    EXECUTE IMMEDIATE 'CREATE TABLE ' ||g_user||'.T_Task1A_Roles_w_User_IDs  AS
    SELECT ROWNUM AS Dummy_Field, USUS_ID AS Task1A_Role, User_ID AS Task1A_User_ID
    FROM Task1A_Roles_w_User_IDs';

    EXECUTE IMMEDATE 'SELECT count(1) FROM T_Task1A_Roles_w_User_IDs' 
        INTO v_Count_Task1A;
    /*more operations like this*/
  END;
  /* more code and nested blocks*/
END;

答案 1 :(得分:3)

动态sql中需要SELECT INTO

DECLARE
  g_user varchar2(30) := 'schema';
BEGIN
  /* more code and nested blocks*/
  DECLARE
    v_Count_Task1A number(6);
  BEGIN

    EXECUTE IMMEDIATE 'CREATE TABLE ' ||g_user||'.T_Task1A_Roles_w_User_IDs  AS
    SELECT ROWNUM AS Dummy_Field, USUS_ID AS Task1A_Role, User_ID AS Task1A_User_ID
    FROM Task1A_Roles_w_User_IDs';

    EXECUTE IMMEDIATE '
    SELECT count(1) 
    FROM T_Task1A_Roles_w_User_IDs'
    INTO v_Count_Task1A;
    /*more operations like this*/
  END;
  /* more code and nested blocks*/
END;