EXECUTE失败不会继续下一步

时间:2015-11-06 06:51:41

标签: postgresql

我创建了一个函数remove_tables,如下所示

CREATE OR REPLACE FUNCTION remove_tables (integer)
    RETURNS void AS
$BODY$DECLARE    
    _id ALIAS FOR $1;
BEGIN
    EXECUTE 'DROP TABLE something_' || _id || ' CASCADE';
    DELETE FROM lot WHERE id = _id ;
END;$BODY$
    LANGUAGE plpgsql VOLATILE
    COST 100;
ALTER FUNCTION delete_tables(integer)
    OWNER TO postgres;

我的问题是,EXECUTE可能会失败,但我仍然想继续使用DELETE语句(DELETE FROM lot WHERE id = _id;)

我尝试使用PERFORM' DROP TABLE的东西_' || _id || ' CASCADE&#39 ;;但是没有给出我想要的东西

无论成功与否,我都可以做任何事情来执行一条陈述,还是继续其他陈述

2 个答案:

答案 0 :(得分:1)

我已经尝试过@a_horse_with_no_name和@Onots指出的异常陷阱,使用异常陷阱工作良好

我也尝试过@Onots提到的其他方法检查表是否存在,也运行良好

由于我不确定捕获异常会对性能产生任何影响,我已经使用了在删除表之前检查表的代码

CREATE OR REPLACE FUNCTION remove_tables (integer)
    RETURNS void AS
$BODY$DECLARE    
    _id ALIAS FOR $1;
BEGIN
    IF EXISTS(SELECT * FROM information_schema.tables WHERE table_name = something_' || _id) THEN
        EXECUTE 'DROP TABLE something_' || _id || ' CASCADE';
    ENDIF;
    DELETE FROM lot WHERE id = _id ;
END;$BODY$
    LANGUAGE plpgsql VOLATILE
    COST 100;
ALTER FUNCTION delete_tables(integer)
    OWNER TO postgres;

答案 1 :(得分:0)

您需要在预期失败的块周围进行异常处理。

CREATE OR REPLACE FUNCTION remove_tables (integer)
    RETURNS void AS
$BODY$DECLARE    
    _id ALIAS FOR $1;
BEGIN
    BEGIN
    EXECUTE 'DROP TABLE something_' || _id || ' CASCADE';
    EXCEPTION WHEN read_only_sql_transaction THEN
    -- Do nothing
    END;
    DELETE FROM lot WHERE id = _id ;
END;$BODY$
    LANGUAGE plpgsql VOLATILE
    COST 100;
ALTER FUNCTION delete_tables(integer)
    OWNER TO postgres;

请参阅http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html上的文档(40.6.6。陷阱错误)。

有关例外代码,请参阅http://www.postgresql.org/docs/9.1/interactive/errcodes-appendix.html