我为单行插入创建了一个触发器,但它不适用于多行插入。
这是我的表:
create table tb_pengiriman
(
id_pengiriman char(5) not null primary key
constraint cek_id_pengiriman check (id_pengiriman like('PE[0-9][0-9][0-9]')),
provinsi varchar(30) not null,
kota varchar(30) not null,
harga_ongkir bigint null
constraint cek_harga_ongkir check (harga_ongkir >-1)
);
alter table tb_pengiriman add
constraint cek_kota_banten
check ((provinsi = 'Banten') and (kota in ('Tangerang','Serang','Cilegon','Tangerang Selatan'))),
这是触发器:
create trigger tr_pengiriman
on tb_pengiriman
after insert
as
begin
declare @id_pengiriman char(5),
@provinsi varchar(30),
@kota varchar(30);
select @id_pengiriman = id_pengiriman from inserted;
select @provinsi = provinsi from inserted;
select @kota = kota from inserted;
exec sp_pengiriman @id_pengiriman,@provinsi,@kota;
end
go
create procedure sp_pengiriman
@id_pengiriman char(5),
@provinsi varchar(30),
@kota varchar(30)
As
Begin
--proses kalkulasi ongkos kirim
if(@kota = 'Tangerang')
begin
update tb_pengiriman
set harga_ongkir = 20000
where id_pengiriman = @id_pengiriman
end
else if(@kota = 'Serang')
begin
update tb_pengiriman
set harga_ongkir = 50000
where id_pengiriman = @id_pengiriman
end
else if(@kota = 'Tangerang Selatan')
begin
update tb_pengiriman
set harga_ongkir = 15000
where id_pengiriman = @id_pengiriman
end
else if(@kota = 'Cilegon')
begin
update tb_pengiriman
set harga_ongkir = 30000
where id_pengiriman = @id_pengiriman
end
else
begin
rollback transaction
print 'kota tidak terdaftar'
end
end
go
此代码适用于单行插入,但是当我尝试执行多行插入时,所有行都会更改为相同的触发器过程更新查询。
如何使此查询适用于多行插入以及单行插入?
答案 0 :(得分:1)
您可以通过使用计算列简化大约1000%。这里根本不需要触发器。您的约束强制kota的值只是这四个值中的一个。这应该完成你想要做的事情而不需要任何触发器等。
create table tb_pengiriman
(
id_pengiriman char(5) not null primary key
constraint cek_id_pengiriman check (id_pengiriman like('PE[0-9][0-9][0-9]')),
provinsi varchar(30) not null,
kota varchar(30) not null,
harga_ongkir as case kota when 'Tangerang' then 20000
when 'Serang' then 50000
when 'Tangerang Selatan' then 15000
when 'Cilegon' then 30000
end persisted
constraint cek_harga_ongkir check (harga_ongkir >-1)
);