在oracle中动态填充变量值

时间:2018-10-31 21:41:29

标签: oracle plsql oracle11g

我有四个表,如下所示:我想在表test中插入变量值v_col。当我尝试运行代码时,此变量名存储在另一个表test_lkp中。如何实现这一目标。

DROP TABLE TEST ;
DROP TABLE TEST_LKP;
DROP TABLE TEST_REF;
DROP TABLE TEST_Q;
CREATE TABLE TEST (COL VARCHAR2(10));
CREATE TABLE TEST_LKP (COL VARCHAR2(10));
CREATE TABLE TEST_REF (VAL VARCHAR2(10));
CREATE TABLE TEST_Q (ENAME VARCHAR2(10));
INSERT INTO TEST_LKP VALUES ('v_col');
INSERT INTO TEST_REF VALUES ('ENAME');
INSERT INTO TEST_Q VALUES ('TOM');
INSERT INTO TEST_Q VALUES ('JIM');
INSERT INTO TEST_Q VALUES ('MARK');

COMMIT;

实际代码:

  SET SERVEROUTPUT ON;
declare

   v_col  VARCHAR2(30);
    BEGIN
      SELECT VAL INTO v_col FROM TEST_REF;  
    dbms_output.put_line(v_col);

EXECUTE IMMEDIATE 
 ' INSERT  INTO TEST  SELECT '|| V_COL ||' FROM TEST_Q ' ;

END;
/

期望是通过查找表动态构建insert语句,以便可以通过查找表来处理列中的任何更改,而不用修改脚本。    为此,我创建了具有与TEST相同结构的查找表TEST_LKP,并插入了与V_COL相同的值。

这是我尝试过的

SET SERVEROUTPUT ON;
declare
   v_col  VARCHAR2(30);
   q VARCHAR2(1000);
  CURSOR c1 IS
SELECT
      'INSERT  INTO TEST '
      ||   
    'SELECT ' || COL || ' FROM TEST_Q '  DMLS   
    FROM TEST_LKP;
  BEGIN
  SELECT val INTO v_col FROM TEST_REF;  
    dbms_output.put_line(v_col);
  FOR i IN c1
   loop
  dbms_output.put_line(i.DMLS);
  execute immediate i.dmls;
  end loop;
END;
/

erorr:

Error report -
ORA-00904: "V_COL": invalid identifier
ORA-06512: at line 17
00904. 00000 -  "%s: invalid identifier"
*Cause:   
*Action:
ENAME
INSERT  INTO TEST SELECT v_col FROM TEST_Q

预期:

i want v_col to be replaced with ENAME as

    INSERT  INTO TEST SELECT ENAME FROM TEST_Q

对此有什么解决方案?

0 个答案:

没有答案