我正在使用IBM DB2,我有以下触发器,在插入同一个表后更新Sales表中的列
PriceSize 表:
create table PriceSize
(
P_size varchar(20) primary key not null,
P_Price decimal(5,2)
);
CombosAndPromotions 表:
Create table CombosAndPromotions
(
CP_ID char(4) primary key not null,
CP_Price decimal(5,2),
CP_Type varchar (15),
CP_Description long varchar
);
销售表
create table sales(
FID char(3) not null,
CID int not null,
PID char(3),
P_size varchar(20),
CP_ID char(4),
Quantity int,
Price Decimal(5,2) with default 0,
FOREIGN key (FID) references Franchise,
FOREIGN key (CID) references Customer,
FOREIGN key (PID) references Product,
FOREIGN key (P_size) references PriceSize,
FOREIGN key (CP_ID) references CombosAndPromotions
);
触发器
create trigger calculate_Price
after insert on sales
referencing new as n
for each row mode db2sql
begin atomic
if n.CP_ID is null then
update Sales s
set Price = (select Pricesize.P_price * s.Quantity
from Pricesize
where s.P_size = Pricesize.P_size);
else
update Sales s
set price = (select CombosAndPromotions.CP_price
from CombosAndPromotions
where s.CP_ID = CombosAndPromotions.CP_ID);
end if;
end@
但问题是这个触发器不仅更新了插入的所有行。 我想得到一些帮助,如何使它只影响插入的行。谢谢
答案 0 :(得分:3)
未经测试,但类似:
create trigger calculate_Price
before insert on sales
referencing new as n
for each row
mode db2sql
set price = case when n.CP_ID is null then
( select ps.P_price * n.Quantity
from Pricesize ps
where n.P_size = ps.P_size )
else
( select cp.CP_price
from CombosAndPromotions cp
where n.CP_ID = cp.CP_ID )
end @
在之前的触发器中,您只影响要插入的行。一些测试数据:
insert into PriceSize (p_size, p_price) values ('a',10.0);
insert into CombosAndPromotions (CP_ID, cp_price) values ('b',20.0);
insert into sales (FID, CID, P_size, cp_id, quantity, price) values ('x',1,'a',null,5,100);
insert into sales (FID, CID, P_size, cp_id, quantity, price) values ('y',2,null,'b',5,100);
select * from sales;
FID CID PID P_SIZE CP_ID QUANTITY PRICE
--- ----------- --- -------------------- ----- ----------- -------
x 1 - a - 5 50.00
y 2 - - b 5 20.00
2 record(s) selected.
for FID=X cp_id is null so the price = 10 * 5 = 50
for FID=y cp_id is not null so the price = 20
correct?