【问题标题】:Postgresql Exception LoggingPostgresql 异常记录
【发布时间】:2022-11-02 10:48:13
【问题描述】:

需要帮助来处理以下要求。

我们需要处理可能出现在 pl sql 块中的异常,并将 select 语句中的某些值记录到量身定制的表 - audit_log 中。 例如:

audit_log 表结构: col1,stored_procedure_name,error_code

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 值传递给异常。

【问题讨论】:

    标签: postgresql exception plpgsql


    【解决方案1】:

    在游标循环内创建一个嵌套(内部块)。然后将您的exception 处理放在此块内。 创建或替换过程 sp_temp() 语言 plpgsql 作为$$ 宣布 开始 /* 遍历 table_a 中的数据 */ 对于 sq in(从 table_a a 中选择 a.column1,a.column2..a.columnn) 环形

           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;
    $procedure$;
    

    注意:注意when others 作为异常块中的唯一谓词。您可能希望处理某些情况并继续,而其他情况则中止处理。仅将when others 用作最后的手段。

    【讨论】:

    • 它无法工作 - RAISE 将插入回滚到 audit_log 表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2014-02-28
    • 2015-10-19
    • 2014-02-20
    相关资源
    最近更新 更多