如何根据用户的输入动态创建表?

时间:2016-10-05 10:00:19

标签: sql oracle plsql

这是我比较2个表的存储过程:

我正在动态接收表名和要比较的列

create or replace 
PROCEDURE SP_TBL_COMPARE_TEST(r_cursor OUT sys_refcursor,
SRC_TBL_NAME IN VARCHAR2,
TGT_TBL_NAME IN VARCHAR2,
SRC_COLS     IN VARCHAR2,
TGT_COLS     IN VARCHAR2) IS   CNT1     NUMBER(5);  CNT2     NUMBER(5); CNT3     NUMBER(5);
SQL_TEXT VARCHAR(1000);
BEGIN
  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' ||SRC_TBL_NAME INTO CNT1;
  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' ||TGT_TBL_NAME INTO CNT2;
  dbms_output.put_line('counted: ' || cnt1);
  dbms_output.put_line('counted: ' || cnt2);
  IF CNT1 != CNT2 THEN
    dbms_output.put_line('count is not maching');
  ELSE
    SQL_TEXT := 'SELECT COUNT(*) FROM ((SELECT * FROM '|| SRC_TBL_NAME ||' MINUS SELECT * FROM '|| TGT_TBL_NAME || ') UNION ALL (SELECT * FROM '|| TGT_TBL_NAME|| ' MINUS  SELECT * FROM '|| SRC_TBL_NAME || '))';
    EXECUTE IMMEDIATE SQL_TEXT INTO CNT3;
    dbms_output.put_line(SQL_TEXT);
    dbms_output.put_line('No of non matching rows: ' || cnt3);
OPEN R_CURSOR FOR '(SELECT '|| SRC_COLS ||' FROM '|| SRC_TBL_NAME ||' MINUS SELECT '|| TGT_COLS ||' FROM '|| TGT_TBL_NAME || ') UNION  (SELECT '|| TGT_COLS ||' FROM '|| TGT_TBL_NAME|| ' MINUS  SELECT '|| SRC_COLS ||' FROM '|| SRC_TBL_NAME || ') ';
END IF;
END;

我必须根据用户输入的cols动态创建表,并在源和目标之间插入不匹配的记录。你能帮忙怎么做吗?

每次用户运行proc

时,列值都可能会更改

1 个答案:

答案 0 :(得分:1)

您可以使用EXECUTE IMMEDIATE语句动态创建表。

像这样:

EXECUTE IMMEDIATE 'CREATE TABLE %YOUR_TABLE% AS ' || '%YOUR_QUERY_FOR_NON_MATCHING_ROWS%';