SQL更新数据映射是否成功

Updating whether data mapping successful in SQL

我有两个 table abcxyz。我正在向这些 table 中插入 consolidated_table 数据。

create or replace
PACKAGE body       XX_package_name
AS

procedure move_data
is 

begin

insert into tabe abc
(colum1 ,
column2,
column3)

select column1,column3,column4 from consolidated_table;

EXCEPTION
WHEN OTHERS THEN
  dbms_output.put_line ('ERROR: print_out :: ' || SUBSTR (sqlerrm, 1, 230));

end;

begin

insert into tabe xyz
(colum1 ,
column2,
column3)

select column1,column3,column4 from consolidated_table;

EXCEPTION
WHEN OTHERS THEN
  dbms_output.put_line ('ERROR: print_out :: ' || SUBSTR (sqlerrm, 1, 230));

end;


end;

现在我在 consolidated_table 中有 2 列作为 error_messgaeprocessed

我必须更新这些列值,例如,如果数据成功插入 abc/xyz,则应填充 processed 列,如果不成功,则应填充 error_message 列。 知道我应该怎么做......我必须在我的开始块中插入这个逻辑

您可能想要使用游标并循环遍历每个项目,如果它无误地插入到两个 table 中并更新合并的 table 一切都很好,如果有错误它将回滚并使用您指定的错误消息更新合并的 table。

create procedure move_data
is
    temp_cur sys_refcursor;
    tmpCol1 consolidated_tbl.col1%Type;
    tmpCol2 consolidated_tbl.col2%Type;
    tmpCol3 consolidated_tbl.col3%Type;
begin
    begin
        open temp_cur for
        select  col1, col2, col3
        from consolidated_tbl
        where processed = 'N';

        loop
        fetch temp_cur into tmpCol1, tmpCol2, tmpCol3;
        exit when temp_cur%notfound;
            begin
                insert into abc (col1, col2, col3)
                values (tmpCol1, tmpCol2, tmpCol3);

                insert into xyz (col1, col2, col3)
                values (tmpCol1, tmpCol2, tmpCol3);

                update consolidated_tbl
                set processed = 'Y', err_msg = null
                where col1 = tmpCol1;

                exception
                when others then
                begin
                    rollback;
                    dbms_output.put_line('Failure: Rollback.');
                    update consolidated_tbl
                    set processed = 'N', err_msg = 'Could not insert into tables.'
                    where col1 = tmpCol1;
                end;
            end;    
            commit;
        end loop;
    end;
end;

如果您想更细化错误消息以指定 table 它出错的原因,您可以将异常块添加到每个语句,并通过将消息连接在一起来用正确的消息更新消息.然后在最后检查消息是否为空,如果不是,则执行回滚并更新 table 中的消息以获取该记录。

另请注意异常的使用,这只是一个示例,在实际使用中,您应该捕获特定的异常而不仅仅是others。例如,假设您尝试插入 table 并且记录已经存在导致 PK 违规。您可能不想在合并 table 中将其标记为失败,但您仍然可以将错误消息添加到其中作为警告或注释。