【发布时间】:2014-12-02 23:21:45
【问题描述】:
我有两个表foo 和bar,还有一个after trigger 在foo 上,它改变了bar 表上的一些东西。
create table foo(id serial primary key, _key char(128) not null);
create table bar(id bigserial primary key, _key_p char(256) not null);
所以当我有一个事务时,例如调用下面的函数,触发器在事务之后触发,而不是语句或相关的 dml 操作。foo 表的触发器:
create or replace function foo_trg_func()returns trigger as $$
declare k_p char(256);begin
k_p:=(select res from prepare_pa(new.key));
insert into bar(_key_p) values(k_p);--insert it to the bar
end $$ language plpgsql;
--
create trigger foo_trg
after insert on foo
for each row execute procedure foo_trg_func();
示例函数/事务
create or replace function `bas`(int,character(128))returns int as $$
-- some commands
with res as (select res as "d" from c_key($1,$2)),
-- attemp to insert into foo and expect the insertion to bar too
ins as (insert into foo(_key) select d from res returning 1) --line[5]
-- check the effect of the foo_trg
select _key_p from bar,res where _key_p=res.d; --line[7]
$$ language sql
触发器被调用,数据被foo触发器插入到bar表中,但是在函数调用之后,我无法在第7行得到触发器插入的结果。
我现在该怎么做?
我还要提一下,可以将触发器标记为代替或之前,但是会引起很多变化,所以我想知道是否可以使用after触发器。 p>
【问题讨论】:
-
不应该是:
ins as (insert into foo(_key) select d from res returning id)? -
是的,先生,错字,谢谢。 @丹尼斯
-
@Denis:添加的
RETURNING子句没有任何作用,CTEins没有被引用。编辑是一个误解,与问题正交。 -
那么你有答案了吗?
-
@ErwinBrandstetter 还没有先生,如果我想忘记触发器并按照您提到的那样做事情,我必须编码几个月并再次重新编码。目前我在调用函数后选择结果,但想知道为什么用这么完美的数据库不可能!?
标签: sql postgresql triggers transactions common-table-expression