【问题标题】:returning value from execute query string in plpgsql从 plpgsql 中的执行查询字符串返回值
【发布时间】:2017-03-24 19:27:36
【问题描述】:

我正在尝试从这样的函数返回一个 ID:

CREATE OR REPLACE FUNCTION fx (myTable text, myValue text) returns int
as $$
DECLARE
  sqlQuery TEXT;
  resultId INT;
BEGIN
  sqlQuery :=
    'INSERT INTO '
    || myTable || ' (id, some_column) values'
    || ' ('
    || 'nextval(' ||  quote_literal('seq_' || myTable) || ')'
    || ',' || myValue
    || ') RETURNING id INTO ' || resultId;

  EXECUTE sqlQuery;
  RETURN resultId;

END;
$$
LANGUAGE plpgsql;

select fx('some_table', 'some_value');

但不工作。

如何从执行的 sql 查询字符串中获取此 ID?

【问题讨论】:

  • 我从未见过 Postgres 错误消息But is not working. 说真的:请在您的问题中提供适当的信息。始终包含您的 Postgres 版本,并始终包含 verbatim 错误消息(如果适用)。

标签: sql postgresql dynamic plpgsql


【解决方案1】:
create or replace function fx (mytable text, myvalue text)
returns int as $body$
declare
    sqlquery text;
    resultId int;
begin

    sqlquery := format ($$
        insert into %I (id, some_column) values ($1, $2)
        returning id
        $$, mytable
    );
    execute sqlquery
        into resultId
        using nextval('seq_' || mytable), myvalue;
    return resultId;

end;
$body$ language plpgsql;

使用%I format 说明符传递标识符,使用execute using 传递数据参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多