小编典典

将UPSERT插入具有动态表名的表中

sql

将UPSERT插入表格的任何更好的方法,都提供:

  • 数据更新速度约为1行/秒
  • 表名是DYNAMIC,使用传递给它的ObjectID参数生成

以下过程抛出:“ ORA-00942:表或视图不存在”

CREATE OR REPLACE PROCEDURE
PROCEDURE "SPINSERTDATA"
(
  pObjectID IN RAW,
  pDateTime IN TIMESTAMP,
  pValue IN BINARY_DOUBLE,
)
AS
BEGIN
  Declare
    vQueryInsert VARCHAR2(1000);
    vQueryUpdate VARCHAR2(1000);
    vTableName VARCHAR2(30);
  Begin      
      vTableName := FGETTABLENAME(POBJECTID => pObjectID);
      vQueryUpdate := 'UPDATE '      || vTableName || ' SET "VALUE" = :1';
      vQueryInsert := 'INSERT INTO ' || vTableName || ' ("DTTIME", "VALUE") VALUES (:1, :2)';

      EXECUTE IMMEDIATE vQueryInsert USING pDateTime, pValue;
        EXCEPTION
          WHEN DUP_VAL_ON_INDEX THEN 
            EXECUTE IMMEDIATE vQueryUpdate USING pValue;
  End;
END "SPINSERTDATA";
  • 显然,MERGE不起作用,因为TableName不能是动态的?
  • 我是新手,我编码的第三个月,我在STACKOVERFLOW和Googled中搜寻了3天,尝试各种有趣而绝望的解决方案……即使您发现一个非常相关的链接,也将受到真诚的感谢。

阅读 144

收藏
2021-05-05

共1个答案

小编典典

MERGE与本机动态SQL完美配合(立即执行):

create table so_test(pk number not null primary key, value varchar2(20));

insert into so_test(pk, value) values(1, 'one');

declare
  l_SQL varchar2(4000);
  l_tablename varchar2(4000) default 'so_test';
begin
  l_SQL := 'merge into ' || l_tablename || ' target' ||
    ' using (select 1 pk, ''eins'' value from dual union all
             select 2 pk, ''zwei'' value from dual) source
      on (target.pk = source.pk)
      when matched then 
        update set target.value = source.value
      when not matched then
        insert values(source.pk, source.value)      
  ';
  dbms_output.put_line(l_sql);
  execute immediate l_SQL;
end;

您能否发布使用MERGE时收到的错误消息?

2021-05-05