Postgresql异常记录

cuxqih21  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(146)

在满足以下要求方面需要帮助。
我们需要处理可能出现在pl sql块中的异常,并将select语句中的某些值记录到定制的表audit_log中。例如:
audit_log表结构:col1,存储过程名,错误代码

CREATE OR REPLACE PROCEDURE SP_TEMP()
 LANGUAGE plpgsql
AS $procedure$
declare

begin
    /* loop through the data in table_a */ 
    for sq in (select a.column1,a.column2..a.columnN from table_a a  )

    loop
        /*Do some operations (not shown here) and select data from table_b */
        (                                                                                                                                                  
        select col1, col2, col3 
        from table_b b where 
        b.col1=sq.column1 )                                                                                                                                                  
        /*insert into table_c*/
        insert into table_c
        values(sq.column1,sq.column2,b.col2,b.col3);

    end loop;

   EXCEPTION:
   WHEN OTHERS THEN
    /* Log the failure information to audit_log table */
    insert into audit_log
    values(column1, 'SP_TEMP',SQLERRM)

end

$procedure$
;

如何将column1的值传递给异常?
我们无法将column1值传递给异常。

mf98qq94

mf98qq941#

在游标循环内创建一个嵌套的(内部块)。然后将您的exception处理放在这个块内。

create or replace procedure sp_temp()
     language plpgsql
    as $$
    declare
    begin
        /* loop through the data in table_a */ 
        for sq in (select a.column1,a.column2..a.columnn from table_a a  )
        loop

           begin  -- inner block to allow processing the exception
              /*do some operations (not shown here) and select data from table_b */
              (                                                                                                                                                  
              select col1, col2, col3 
              from table_b b where 
              b.col1=sq.column1 )                                                                                                                                                  
              /*insert into table_c*/
              insert into table_c
              values(sq.column1,sq.column2,b.col2,b.col3);
           exception
               when others then
                /* log the failure information to audit_log table */
                insert into audit_log
                values(sq.column1, 'sp_temp',sqlerrm);

            end; -- inner block   
        end loop;   
    end;
    $$;

注意:请注意when others是例外状况区块中唯一的述词。可能有些状况您想要行程并继续,而有些状况则要中止行程。请将when others当做最后的手段使用。

相关问题