如何使用触发Postgres打印新值

时间:2016-10-04 18:48:59

标签: sql postgresql

我想为Insert操作创建触发器,以及打印插入值的过程。

CREATE TRIGGER added_product_info_trigger
BEFORE INSERT
ON products
EXECUTE PROCEDURE added_product_info();

我的程序

CREATE OR REPLACE FUNCTION added_product_info()
RETURNS trigger
AS
$$
    (Select p.productname, s.companyname from products as p, suppliers as s
    where p.supplierid = s.supplierid)
$$ LANGUAGE SQL;

如何打印插入的值?

1 个答案:

答案 0 :(得分:2)

Sql函数无法返回trigger。您可能想编写一个plpgsql函数。

触发器函数无法生成任何输出(如select查询的结果)。 您可以使用raise notice将一些结果传递给客户端程序:

create or replace function added_product_info()
returns trigger as $$
declare 
    company text;
begin
    select companyname 
    from suppliers
    where supplierid = new.supplierid
    into company;
    raise notice 'inserted: "%" supplied by "%"', new.productname, company;
    return new;
end;
$$ language plpgsql;

仅当触发器声明为new时,才会在触发器函数中显示记录for each row (如果无法访问记录for each statementnew,则默认为old):

create trigger added_product_info_trigger
before insert on products
for each row
execute procedure added_product_info();

如果触发器为before insert for each row,则必须返回new

请注意,客户必须准备好获取并处理通知。 如果您在标准 psql shell程序中运行查询,则会得到:

insert into products values ('some product', 1);
NOTICE:  inserted: "some product" supplied by "company"
INSERT 0 1

阅读: