如何在postgreSQL PL / pgSQL EXECUTE中返回一个值

时间:2016-10-03 23:42:31

标签: postgresql plpgsql

我正在尝试从EXECUTE中返回插入ID。这很好用:

CREATE OR REPLACE FUNCTION public.mytest2()
    RETURNS INTEGER
LANGUAGE plpgsql
AS $function$
DECLARE
    retval  INTEGER;
    RETURNING "DULid" INTO retval;';
BEGIN
    INSERT INTO "dbUpdateLog" (notes) VALUES ($$hello$$) RETURNING "DULid" INTO retval;
    RETURN retval;
END;
$function$

但是,在EXECUTE中执行此操作时出现错误:

CREATE OR REPLACE FUNCTION public.mytest2()
    RETURNS INTEGER
LANGUAGE plpgsql
AS $function$
DECLARE
    retval  INTEGER;
BEGIN
    EXECUTE 'INSERT INTO "dbUpdateLog" (notes) VALUES ($$hello$$) RETURNING "DULid" INTO retval;';
    RETURN retval;
END;
$function$

我需要使用EXECUTE,因为查询将动态生成。这是错误:

ERROR:  syntax error at or near "INTO"
LINE 1: ...Log" (notes) VALUES ($$hello$$) RETURNING "DULid" INTO retva...

在EXECUTE中使用时,如何获得返回值(在本例中特别是插入ID)?

1 个答案:

答案 0 :(得分:4)

使用execute... into...

BEGIN
    EXECUTE 'INSERT INTO "dbUpdateLog" (notes) VALUES ($$hello$$) RETURNING "DULid"'  
    INTO retval;
    RETURN retval;
END;

请参阅Executing Dynamic Commands