首页 > 解决方案 > postgresql上的不一致记录数据

问题描述

我是 postgresql 的新手。我正在尝试学习如何使用触发器和 postgresql 将 sum 插入另一个表。

我想将表 invoice_items 中的数据 current_balance 插入表 tbl_cb

这是我的功能脚本

CREATE OR REPLACE FUNCTION rec_cb_insert() 
RETURNS trigger AS $build_cb_insert$ 
begin
    if new.type = 'CBA_ADJ' then
    INSERT INTO tbl_cb(current_balance)
        select SUM(amount)FROM invoice_items
        WHERE account_id='6015ec0f-4d30-4802-bbcc-ea35c12f93a2' 
        and type='CBA_ADJ';
       end if;
    RETURN new;
END;
$build_cb_insert$ 
LANGUAGE plpgsql;

这是我的触发器

create trigger insert_cb_insert
  after insert
  on invoice_items
  for each row
  execute procedure rec_cb_insert()
;

当我插入没有线程数据列curent_balance一致性的数据时,

没有线程:

图片

但是当我使用线程数据列curent_balance 时不一致。

带螺纹:

图片

一致性_current_balance_table_tbl_cb

unconsistence_current_balance_table_tbl_cb

如何解决?

2019 年 9 月 20 日更新,

这个新的我的功能

    CREATE OR REPLACE FUNCTION public.insert_currentbalance_3()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
 DECLARE
    current_balance numeric;
    BEGIN
        -- Check that empname and salary are given
        IF new.type IS NULL THEN
            RAISE EXCEPTION 'type cannot be null';
        END IF;

         IF  new.account_id IS NULL THEN
            RAISE EXCEPTION 'account_id cannot be null';
        END IF;

        IF new.type = 'CBA_ADJ' then
       EXECUTE'SELECT SUM(amount) FROM invoice_items WHERE 
               account_id= new.account_id and type=new.type new.invoice_id'
              into current_balance;
        insert into balance (invoice_id, balance, invoice_items_id)
        values (new.invoice_id,current_balance,new.invoice_id);
        END IF;
        -- Remember who changed the payroll when
        -- NEW.last_date := current_timestamp;
        --  NEW.last_user := current_user;
        RETURN NEW;
    END;
$function$
;

这是我的触发器

CREATE TRIGGER insert_current_balance AFTER
INSERT 
ON
FOR EACH ROW
EXECUTE PROCEDURE function_insert_currentbalance3();

现在我得到错误 原因:org.postgresql.util.PSQLException:错误:由于事务之间的读/写依赖关系而无法序列化访问。

如何解决?:(

标签: postgresqldatabase-trigger

解决方案


推荐阅读