且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在提交插入之前编写触发器以更新同一表中的行?

更新时间:2022-12-12 16:22:00

正如@Filipe Silva所说,您无法修改

As @Filipe Silva said, you can't modify a table in a trigger that is invoked on that table.

您可以通过为股票和股价历史记录使用单独的表来解决此问题,这很可能是无论如何都是个好主意。 股票表每个股票项及其当前价格保存一行,并且该表上的触发器维护股票价格历史记录$ c $中的记录c>插入或更新库存中的行。

You can work around this by having separate tables for the stock and for the stock price history, which is probably a good idea in any case. The stock table holds one row per stock item, along with its current price, and triggers on that table maintain the records in stockpricehistory as rows in stock are inserted or updated.

http://sqlfiddle.com/#!2/55c626/1

create table stock (
  stockId int primary key,
  price numeric(5, 2));

create table stockpricehistory (
  stockId int,
  price numeric(5,2),
  dateStart datetime,
  dateEnd datetime);

create trigger t_si before insert on stock
for each row
  insert into stockpricehistory values (new.stockId, new.price, current_timestamp, null);

create trigger t_su before update on stock
for each row begin
  update 
    stockpricehistory 
  set
    dateEnd = current_timestamp
  where
    stockId = new.stockId and
    dateEnd is null;
  insert into stockpricehistory values (new.stockId, new.price, current_timestamp, null);
end;