如何写一个触发器,它在insert
在table3
外观的table1
,如果code
和id
具有price
第一那里,更新price
的table3
相应。但是,如果id
+code
不能被随后发现它看起来在table2
对id
并使用该价格来计算总price
并更新price
在table3
该插件。
表格1
| id | code | price |
|----|------|-------|
| 1 | fire | 3 |
| 2 | ice | 4 |
| 3 | air | 5 |
表2
| id | price |
|----|-------|
| 1 | 8 |
| 2 | 9 |
表3
| id | code | qty | price |
|----|------|-----|-------|
| 1 | fire | 2 | | -- price = 2 * 3 = 6
| 2 | none | 3 | | -- price = 3 * 9 = 27
在触发功能中,应使用if exists
它进行检查。您可以编写触发函数,如下所示:
CREATE FUNCTION update_price()
RETURNS trigger AS $$
BEGIN
if exists (select price from table1 where code=new.code and id=new.id) then
new.price= new.qty * (select price from table1 where code=new.code and id=new.id);
else
new.price= new.qty * (select price from table2 where id=new.id);
end if;
return new;
END;
$$ LANGUAGE plpgsql;
然后,您可以table3
按以下方式编写触发器:
create trigger update_price
before insert
on table3
for each row
execute procedure update_price();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句