sql - 从 plpgsql 中的执行查询字符串返回值

标签 sql postgresql dynamic plpgsql

我正在尝试从这样的函数返回一个 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?

最佳答案

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 的说明符传递数据参数。

关于sql - 从 plpgsql 中的执行查询字符串返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533186/

相关文章:

sql - 通过流分析将带有数组的流传递到 SQL 中的多行

python-3.x - Django:在 postgres 中的表达式上添加唯一索引

sql - 已列出但不可选择的 Postgresql 表

ipad - 弹出窗口中的导航 Controller

c# - 动态对象,可持久保存到 Azure 并可通过 Dynamic Linq 进行查询

mysql - 选择具有多个条件的多列

sql - 如何计算 SQL 中特定值之间的差异的平均值?

python - Flask 和 SQLAlchemy 在 PostgreSQL 的事务连接中导致大量 IDLE

c - 如何在 C 中使用动态多维数组?

sql - 表名作为postgresql中的变量