PostgreSQL - 如何使用 varchar 参数调用存储过程

6

我正在尝试在Postgresql 12中创建存储过程:

CREATE OR REPLACE PROCEDURE trans_buy(
        _name_client varchar(25),
        _id_product smallint,
        _mount smallint
    )
    LANGUAGE plpgsql
    AS
    $$

    BEGIN 
        INSERT INTO invoices (cliente) VALUES(_name_client);
        INSERT INTO invoices_details (id_invoice, id_product, mount) VALUES (1, _id_product, _mount, 100);
    END
    $$

但是当我尝试这样调用此存储过程时:

CALL trans_buy('james', 3, 10)

我收到了这个错误信息:

不存在存储过程 << trans_buy(unknown, integer, integer) >>

提示: 没有匹配参数名和类型的存储过程。可能需要添加显式类型转换。


你具体遇到了哪个错误? - GMB
当我调用存储过程时,第一个参数出现了显式转换错误。 - k16style
请编辑您的问题,包括整个和确切的错误信息。 - GMB
完成,请查看。 - k16style
1个回答

6

您可能需要将整数值明确转换为 smallint

call trans_buy('james', 3::smallint, 10::smallint);

我假设invoice_details中的目标列也是smallint。另一种方法是让过程接受int,并在insert时间转换:

CREATE OR REPLACE PROCEDURE trans_buy(
    _name_client varchar(25),
    _id_product int,
    _mount int
) LANGUAGE plpgsql
AS $$
BEGIN 
    INSERT INTO invoices (cliente) VALUES(_name_client);
    INSERT INTO invoices_details (id_invoice, id_product, mount) VALUES (1, _id_product::smallint, _mount::smallint);
END
$$

请注意,您的第二个插入为三个列提供了四个值。我已经尝试进行了调整。


另外需要强调的是,在Postgres中您并不真正需要使用子查询来完成此操作。您可以在单个查询中运行多个DML操作,使用公共表达式:

with 
    -- CTE: query parameters
    params(cliente, id_product, mount) as (values ('james', 3, 10)),
    
    -- CTE: insert to invoices
    inv as (insert into invoices (cliente) select cliente from params)

-- insert to invoice details
insert into invoice_details (id_invoice, id_product, mount) 
select 1, id_product, mount from params

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接