使用游标创建表并插入值(PL / SQL)

时间:2015-03-11 00:03:38

标签: sql oracle plsql

我对PL / SQL比较陌生。我编写了PL / SQL代码来创建一个表,并根据另一个表提取的结果向其中插入几个值。

DECLARE

nCount NUMBER;
v_sql VARCHAR2(4000);


BEGIN
SELECT count(*) into nCount FROM all_tables where table_name = 'OBJECT_ANALYSIS_T';

dbms_output.put_line(nCount);
IF(nCount <= 0) THEN

BEGIN
  v_sql:='
  create table object_analysis_t
  (
    object_type varchar2(10),
    object_name varchar2(10),
    validity varchar2(10),
    status varchar2(10),
    severity varchar2(10)
  )';
  execute immediate v_sql;
  commit;
END;

DECLARE
  c_object_type VARCHAR2(10);
  c_object_name USER_OBJECTS.OBJECT_NAME%type;
  c_validity USER_OBJECTS.STATUS%type;
  c_status VARCHAR2(5);
  c_severity VARCHAR2(10);


CURSOR c_user_objects is
  SELECT object_name,status FROM USER_OBJECTS WHERE object_type IN ('FUNCTION');


  BEGIN
    c_object_type:= 'FUNCTION';
    OPEN c_user_objects;
    LOOP
      FETCH c_user_objects INTO c_object_name, c_validity;

      IF( c_validity = 'VALID') THEN 
        c_status:= 'PASS';
      ELSIF( c_validity = 'INVALID') THEN
        c_status:= 'FAIL';
      ELSE
        c_status:= 'FAIL';
      END IF;

      EXIT WHEN c_user_objects%notfound;
      --INSERT THE VALUES IN THE CREATED TABLE
      BEGIN
      execute immediate 'INSERT INTO OBJECT_ANALYSIS_T VALUES (c_object_type, c_object_name, c_validity, c_status,c_severity) '; 
      END;

      END LOOP;
      CLOSE c_user_objects;
  END;

  END IF;
  END;
  /

现在,当我执行上面的代码时,会创建表,但变量中的值不会插入到新表中。

我收到此错误

ORA-00984: column not allowed here

任何帮助将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:1)

您的PL / SQL变量名称超出了动态SQL语句的范围。您需要使用using子句将值作为绑定变量传递:

execute immediate 'INSERT INTO OBJECT_ANALYSIS_T VALUES '
  || '(:object_type, :object_name, :validity, :status, :severity)'
  using c_object_type, c_object_name, c_validity, c_status,c_severity;

指定目标表列名称也是一种好习惯。除非你真的需要,否则不使用动态SQL甚至是更好的做法,正如Justin Cave所提到的,你通常会以更加可控的方式创建模式对象,而不是在运行时或按需创建模式对象。使用动态SQL会隐藏编译错误直到运行时,并且可能更难调试。