Oracle中的合并不会插入/更新任何行

时间:2013-04-19 13:34:26

标签: sql oracle plsql merge

您能否建议,此查询有什么问题?它始终提取0条记录而不插入数据。 我检查了选择查询,它正在返回行。但我不确定合并部分发生了什么错误,它没有插入/更新表。

ExtractType         NUMBER(9);
RecordsExtracted    NUMBER(9);
CurStatus           NUMBER(9);
StartDate           date;
ErrorMessage        NVARCHAR2(1000);
LastExtrctTimestamp DATE;
BEGIN
StartDate := sysdate;
ExtractType := 79;

-- Fetching the Last Extract Time Stamp 
Select  max(ExtractTimestamp) INTO LastExtrctTimestamp from ExtractRecords where Status = 2 and  ExtractRecords.ExtractType= ExtractType;

IF LastExtrctTimestamp IS NULL
THEN LastExtrctTimestamp := To_Date('01/01/1901', 'MM/dd/yyyy');
END IF;

MERGE INTO Table MCTH
USING (
    SELECT
            val1, val2, val3, .... val1
    FROM
            View_RPT
    WHERE TransitionDate >= LastExtrctTimestamp
) Core
ON(MCTH.valId= Core.ValId)
WHEN MATCHED THEN
UPDATE SET 
    MCTH.val1= Core.val1,
    MCTH.val2= Core.val2,
    MCTH.val3= Core.val3,
    .
    .
    MCTH.val4= Core.val4
WHEN NOT MATCHED THEN
INSERT (MCTH.val1,MCTH.val2,MCTH.val3,MCTH.val4,
        ...,MCTH.val5)
VALUES (Core.val1,Core.val2,Core.val3,Core.val4,
        ...,Core.val5);
RecordsExtracted := SQL%RowCount;       

DBMS_OUTPUT.put_line('MCTH Records Merged:' || RecordsExtracted);

COMMIT;

END;

1 个答案:

答案 0 :(得分:1)

将pl / sql逻辑转换为merge语句,您可以测试内核是否更容易返回您期望的内容:

merge into
  margincalltransitionhistory mcth
using (
  select
    margincalltransitionhistoryid,
    margincallid,
    fromworkflowstatename,
    toworkflowstatename, 
    transitiondate,
    transitionbyname,
    transitioncomment
  from
    margincalltranhistory_rpt
  where
    transitiondate >= (
      select  coalesce(max(extracttimestamp), date '1901-01-01')
      from    extractrecords
      where   status      = 2 and
              extracttype = 79)
  ) core
...

为了上帝的爱,清理你的代码 - 我不知道你如何处理这个烂摊子。