繁体   English   中英

PostgreSQL:从其他表触发 INSERT INTO SELECT

[英]PostgreSQL: Trigger INSERT INTO SELECT from other table

我正在尝试创建一个触发器,每次在源表中创建新行时,它将向目标表添加一个新的行处理条目。

步骤 1 创建目标表:

CREATE TABLE public.destination_table (
                          id serial PRIMARY KEY,
                          created_at TIMESTAMP NOT NULL,
                          sale_id INTEGER NOT NULL,
                          product_id INTEGER NOT NULL,
                          product_name VARCHAR NOT NULL,
                          url VARCHAR NOT NULL, 
                          shop_id VARCHAR NOT NULL,
                          user_id VARCHAR)

步骤 2 创建触发函数:

CREATE OR REPLACE FUNCTION triger_function() RETURNS TRIGGER AS
$BODY$
BEGIN
INSERT INTO public.destination_table ( created_at, sale_id, product_id, product_name, url, shop_id, user_id)
 SELECT created_at,
        sale_id,
        product_id,
        product_name,
        split_part(url::text, '?'::text, 1) AS url,
        shop_id,
        ((((((((data #>> '{}'::text[])::jsonb) #>> '{}'::text[])::jsonb) -> 'local_storage'::text) -> 'data'::text) #>> '{}'::text[])::jsonb) ->> 'user_id'::varchar AS user_id
   FROM source_table;
           RETURN new;
END;
$BODY$
language plpgsql;

** 函数内部的 Select 查询在单次运行时正常工作。

步骤 3 创建触发器:

CREATE TRIGGER trigger_records
     AFTER INSERT ON public.source_table
     FOR EACH ROW
     EXECUTE PROCEDURE triger_function();

问题是 Trigger 不起作用,这意味着它不会在目标表中记录新条目。 无法弄清楚错误在哪里。

您应该在触发器函数中使用 NEW 记录来引用新插入的数据而不是选择,即:

CREATE OR REPLACE FUNCTION triger_function() RETURNS TRIGGER AS
$BODY$
BEGIN
INSERT INTO public.destination_table ( created_at, sale_id, product_id, product_name, url, shop_id, user_id)
VALUES(NEW.created_at,
    NEW.sale_id,
    NEW.product_id,
    NEW.product_name,
    split_part(NEW.url::text, '?'::text, 1),
    NEW.shop_id,
    ((((((((NEW.data #>> '{}'::text[])::jsonb) #>> '{}'::text[])::jsonb) -> 'local_storage'::text) -> 'data'::text) #>> '{}'::text[])::jsonb) ->> 'user_id'::varchar)
       RETURN new;
END;
$BODY$
language plpgsql;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM