【问题标题】:Calling a procedure with inout parameters from psql从 psql 调用带有 inout 参数的过程
【发布时间】:2021-12-14 15:05:05
【问题描述】:

给定下表

CREATE TABLE dt_test.dt_integer (
    id serial NOT NULL,
    test_col integer,
    test_comment varchar,
    CONSTRAINT dt_integer_pk PRIMARY KEY ( id ) ) ;

以及插入数据的过程

CREATE PROCEDURE dt_test.integer_insert (
    a_id inout int,
    a_integer in integer,
    a_comment in varchar,
    a_err inout varchar ( 200 ) )
SECURITY DEFINER
LANGUAGE plpgsql
AS $$
DECLARE

BEGIN

    WITH inserted AS (
        INSERT INTO dt_test.dt_integer (
                test_col,
                test_comment )
            VALUES (
                a_integer,
                a_comment )
            RETURNING id
    )
    SELECT id
        INTO a_id
        FROM inserted ;

END ;
$$ ;

可以/如何从 psql 调用该过程?在 Oracle 中,使用 sql-plus 如下所示:

DECLARE
    a_err varchar2 ( 200 ) ;
    a_id number ;
    
BEGIN

    dt_test.integer_insert ( a_id, 13, 'A prime example', a_err ) ;

    dbms_output.put_line ( 'The new ID is: ' || a_id ) ;

END ;

(我不想认为 sql-plus 可以做 psql 做不到的事情)

【问题讨论】:

  • 附带说明:CTE 并不是必需的:insert into ... returning into a_id; 也可以。

标签: postgresql psql


【解决方案1】:

嗯,你会在 PL/pgSQL 中做同样的事情:

set client_min_messages=notice;

do
$$
declare
   a_err text;
   a_id int;
begin
   call dt_test.integer_insert(a_id, 13, 'A prime example', a_err);
   raise notice 'The new ID is: %', a_id;
end;
$$
;

【讨论】:

  • 请注意,定义“a_err text”会导致“过程参数“a_err”是输出参数,但相应的参数不可写”错误。但是,将定义更改为“a_err varchar(200)”是可行的。
  • @gsiems:啊,我忽略了它是varchar(200) - 但一般来说,我会使用text 作为这样的参数开始。无需将其限制为 200 个字符(在这种情况下,文本与 varchar 相比没有性能或内存劣势)
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 2014-10-28
  • 2011-07-29
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 2011-07-06
  • 2015-01-07
相关资源
最近更新 更多