PostgreSQL过程返回查询没有结果数据的目的地

时间:2019-10-09 15:17:17

标签: postgresql procedure

我正在构建一个过程,该过程在插入后由触发器调用,并且在其主体中使用select语句时发生错误。

当我不使用select来获取值时,触发器调用此过程时没有错误:

BEGIN;

CREATE OR REPLACE FUNCTION calc_virtual()
RETURNS trigger
LANGUAGE plpgsql

AS $function$ 

DECLARE
    _virtual RECORD;
    _value_calc DECIMAL;
    _complet BOOLEAN;

BEGIN
    _value_calc = 0

    FOR _virtual IN SELECT value
                      FROM virtual
                     WHERE id = NEW.id 
    LOOP                             
        _value_calc = _value_calc-(value * 1.5);            
    END LOOP;

    INSERT INTO appointment (value) VALUES (_value_calc);

    RETURN NEW;
END;

$function$;

COMMIT;

当我使用select获取值时,触发器调用此过程会发生错误:

BEGIN;

CREATE OR REPLACE FUNCTION calc_virtual()
RETURNS trigger
LANGUAGE plpgsql

AS $function$ 

DECLARE
    _virtual RECORD;
    _value_calc DECIMAL;
    _complet BOOLEAN;

BEGIN

    FOR _virtual IN SELECT value
                      FROM virtual
                     WHERE id = NEW.id 
    LOOP
        _value_calc = 0;
        _complet = TRUE;      

        SELECT  value_active
        FROM    appointment_virtual
        WHERE   name = _virtual.name;

        IF FOUND THEN
            _value_calc = _value_calc-(value_active * 1.5);
        ELSE
            _complet = False;
        END IF;            
    END LOOP;

    IF _complet THEN
        INSERT INTO appointment (value) VALUES (_value_calc);
    END IF;

    RETURN NEW;
END;

$function$;

COMMIT;

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您必须在PL / pgSQL中使用SELECT ... INTO。不会神奇地创建任何变量value_active

SELECT  value_active INTO _active
FROM    appointment_virtual
WHERE   name = _virtual.name;

IF FOUND THEN
     _value_calc = _value_calc-(_active * 1.5);
...

您必须在_active部分中声明DECLARE