用光标写入表(表名作为参数)

时间:2019-06-24 13:27:02

标签: sql oracle variables fetch

如何使用名称为给定的CURSOR插入表中? 谢谢

PROCEDURE delta (pTableName IN VARCHAR2, pStichTag  IN DATE) IS 
   lTabName :=  VARCHAR(30);
   v_stmt_str := VARCHAR(4000); 
   cCursor SYS_REFCURSOR;
   BEGIN
       lTabName :=  substr(pTableName,5);
       v_stmt_str := 'SELECT * FROM '|| lTableName ||' WHERE dwh_date =     
       to_date('||pStichTag||','DD.MM.YY');

   OPEN cCursor  FOR v_stmt_str USING 'MANAGER';
   LOOP
       FETCH cCursor INTO pTableNAME%ROWTYPE;
       -- UPATE pTableName SET some WHERE this line
   END LOOP;
CLOSE cCursor;

2 个答案:

答案 0 :(得分:1)

您需要使用EXECUTE IMMEDIATE来执行更新:

EXECUTE IMMEDIATE 'UPDATE ' || pTableName ||
                  ' SET SOME_COLUMN = 12345 WHERE SOME_OTHER_COLUMN = ''xyz''';

但是,您将不得不重新执行光标逻辑。由于您不知道表名,因此不知道在打开游标之前将要获取哪些字段,因此您将不得不对要获取的字段名进行硬编码,而不是使用* 。如果您不喜欢这种方式,则必须使用DBMS_SQL程序包,该程序包具有更大的灵活性-但我会警告您,它的使用相当复杂。

好运。

答案 1 :(得分:0)

正确的代码段

PROCEDURE delta (pTableName IN VARCHAR2, pStichTag  IN DATE) 
IS 
   lTabName  VARCHAR(30); -- removed :=
   v_stmt_str VARCHAR(4000); -- removed :=
   cCursor SYS_REFCURSOR;
   BEGIN
       lTabName :=  substr(pTableName,5); -- I dont understand why only first five digits of table name is used. May be your logic
       v_stmt_str := 'SELECT * FROM '|| lTableName ||' WHERE dwh_date =     
       to_date('''||pStichTag||''',''DD.MM.YY'')'; -- added few ' for proper string concatenation

   OPEN cCursor  FOR v_stmt_str USING MANAGER; -- removed ' from MANAGER, MANAGER must be some variable and for your cusrsor, there is no bind variable so there is no need of USING clause at all
-- You can use just: OPEN cCursor  FOR v_stmt_str;
   LOOP
       FETCH cCursor INTO pTableNAME%ROWTYPE;
       -- UPATE pTableName SET some WHERE this line
   END LOOP;
CLOSE cCursor;

我希望这会有用。

干杯!