Postgresql异常记录

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

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

  1. CREATE OR REPLACE PROCEDURE SP_TEMP()
  2. LANGUAGE plpgsql
  3. AS $procedure$
  4. declare
  5. begin
  6. /* loop through the data in table_a */
  7. for sq in (select a.column1,a.column2..a.columnN from table_a a )
  8. loop
  9. /*Do some operations (not shown here) and select data from table_b */
  10. (
  11. select col1, col2, col3
  12. from table_b b where
  13. b.col1=sq.column1 )
  14. /*insert into table_c*/
  15. insert into table_c
  16. values(sq.column1,sq.column2,b.col2,b.col3);
  17. end loop;
  18. EXCEPTION:
  19. WHEN OTHERS THEN
  20. /* Log the failure information to audit_log table */
  21. insert into audit_log
  22. values(column1, 'SP_TEMP',SQLERRM)
  23. end
  24. $procedure$
  25. ;

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

mf98qq94

mf98qq941#

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

  1. create or replace procedure sp_temp()
  2. language plpgsql
  3. as $$
  4. declare
  5. begin
  6. /* loop through the data in table_a */
  7. for sq in (select a.column1,a.column2..a.columnn from table_a a )
  8. loop
  9. begin -- inner block to allow processing the exception
  10. /*do some operations (not shown here) and select data from table_b */
  11. (
  12. select col1, col2, col3
  13. from table_b b where
  14. b.col1=sq.column1 )
  15. /*insert into table_c*/
  16. insert into table_c
  17. values(sq.column1,sq.column2,b.col2,b.col3);
  18. exception
  19. when others then
  20. /* log the failure information to audit_log table */
  21. insert into audit_log
  22. values(sq.column1, 'sp_temp',sqlerrm);
  23. end; -- inner block
  24. end loop;
  25. end;
  26. $$;

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

展开查看全部

相关问题