首页 > 解决方案 > 内部有 Begin End 块的 Postgresql 循环在抛出异常时被中断,同时被拦截;循环应该运行到最后

问题描述

我有这样的功能:

create or replace function produciblepwforregulation(now date, timerange integer, devicename character varying) returns void
    language plpgsql
as $$
BEGIN
    FOR t IN 1..timeRange BY 1
        LOOP
            BEGIN
            insert into values
            (value, time, devicename)
            values (    2200 +
                        600 *
                                round(abs(sin(((t) * 0.042))) + 0.1) *
                                (sin(sin(((t) * 2 / 2.0 / 2.155172413793103 * PI()))) /
                                abs(sin(sin(((t) * 2 / 2.0 / 2.155172413793103 * PI()))))) *
                                (3 - exp(-12.5 + floor((t) * 2 / 2.0 / 2.155172413793103) * 2.155172413793103 * PI() * 2 * round(abs(sin(((t) * 0.042))) + 0.1) - ((t) * 2 * PI())))
                        +
                        600 *
                                abs(round(abs(sin(((t) * 0.042))) + 0.1) - 1) *
                                (sin(sin(((t) / 2.0 / 4.310344827586207 * PI()))) /
                                abs(sin(sin(((t) / 2.0 / 4.310344827586207 * PI()))))) *
                                (3 - exp(-25.5 + floor((t) / 2.0 / 4.310344827586207) * 4.310344827586207 * PI() * 2 * abs(round(abs(sin(((t) * 0.042))) + 0.1) - 1) - ((t) * PI())))
                        + 50 * sin(3 + (t) * 0.092) + 350 * sin(3 + (t) * 0.012),
                    now + t * INTERVAL '1 second' - 1 * INTERVAL '1 milliseconds',
                    devicename);             
              EXCEPTION WHEN others THEN NULL;  -- <- here I expect the funtion will just go ahead with its loop 
              END;  
        END LOOP;        
END

$$;

alter function produciblepwforregulation(date, integer, varchar) owner to postgres;

调用函数时,时间范围作为参数传递,以期望 86400 步

  select produciblepwforregulation('2020-11-18', 86400, '1');

但是,执行在 194 步时停止,可能面临一些异常(内部函数能够发生下溢异常)。我期望异常只是停止循环内的 Begin-End 块,因此我们只是切换到循环中的另一个 t 值,并且执行不应该停止。但它实际上是停止并且永远不会克服导致问题的循环中的 t 值。

PS。我知道它非常未优化,但我真的需要让它作为 postgresql 函数的一部分来执行。

聚苯乙烯。当我调用函数执行时,我在这里绝对看不到错误消息,所以错误(根据我的预期是错误)对我来说是无声的:

在此处输入图像描述

标签: sqlpostgresqlsql-function

解决方案


推荐阅读