0

我正在使用 PostgreSQL 8.4。我的目标是在 PL/pgSQL 的帮助下插入多行,id并将插入记录的 -s 返回到记录集中。

起初,我尝试在一行中执行此操作,对我的permission_create(..)函数使用以下代码:

CREATE FUNCTION permission_create(
  IN method   permission.permission_method % TYPE,
  IN resource permission.permission_resource % TYPE
)
  RETURNS TABLE(id permission.permission_id % TYPE)
AS
  $BODY$
  BEGIN
    RETURN QUERY
      WITH inserted_permission AS (
        INSERT INTO permission (permission_id, permission_method, permission_resource) VALUES (DEFAULT, method, resource)
        RETURNING permission_id
      )
      SELECT
        inserted_permission.permission_id AS id
      FROM inserted_permission;
  END;
  $BODY$
LANGUAGE plpgsql VOLATILE;

但是,我收到以下错误消息:

[2013-07-04 17:38:01] [00000] type reference permission.permission_method%TYPE converted to character varying
[2013-07-04 17:38:01] [00000] type reference permission.permission_resource%TYPE converted to character varying
[2013-07-04 17:38:01] [00000] type reference permission.permission_id%TYPE converted to integer
[2013-07-04 17:38:01] [00000] type reference permission.permission_id%TYPE converted to integer
[2013-07-04 17:38:01] [42601] ERROR: syntax error at or near "INSERT"
  Where: SQL statement in PL/PgSQL function "permission_create" near line 9

我应该如何解决这个问题?有没有办法在多行中做到这一点?

解决方案:

CREATE FUNCTION permission_create(
  IN method   permission.permission_method % TYPE,
  IN resource permission.permission_resource % TYPE
)
  RETURNS TABLE (id INT)
AS
  $BODY$
  BEGIN
    RETURN QUERY
    INSERT INTO permission (permission_id, permission_method, permission_resource)
      VALUES (DEFAULT, method, resource)
    RETURNING permission_id;
  END;
  $BODY$
LANGUAGE plpgsql VOLATILE;
4

1 回答 1

3

PostgreSQL 9.1 支持可更新 CTE。

您不需要使用 CTE(在您的情况下)

postgres=# 创建或替换函数 fx()
返回 SETOF int AS $$
开始
  返回查询插入到 taba(a) 值(1),(2)
    返回 *;
  返回;
结尾;
$$ 语言 plpgsql;
创建函数
postgres=# select * from fx();
 外汇
----
  1
  2
(2 行)
于 2013-07-04T18:47:47.260 回答