FOR EACH ROW
betyder för var och en av de matchade raden som antingen uppdateras eller raderad .
Utlösarens kropp går inte igenom hela tabelldata om det inte finns ett where-villkor i frågan.
Ett fungerande exempel visas nedan:
Skapa exempeltabeller :
drop table if exists tbl_so_q23374151;
create table tbl_so_q23374151 ( i int, v varchar(10) );
-- set test data
insert into tbl_so_q23374151
values (1,'one'),(2,'two' ),(3,'three'),(10,'ten'),(11,'eleven');
-- see current data in table**:
select * from tbl_so_q23374151;
+------+--------+
| i | v |
+------+--------+
| 1 | one |
| 2 | two |
| 3 | three |
| 10 | ten |
| 11 | eleven |
+------+--------+
5 rows in set (0.00 sec)
Exempeltabell för att registrera loopantalet i triggerkroppen :
-- let us record, loop count of trigger, in a table
drop table if exists tbl_so_q23374151_rows_affected;
create table tbl_so_q23374151_rows_affected( i int );
select count(*) as rows_affected from tbl_so_q23374151_rows_affected;
+---------------+
| rows_affected |
+---------------+
| 0 |
+---------------+
Definiera en delete utlösa :
drop trigger if exists trig_bef_del_on_tbl_so_q23374151;
delimiter //
create trigger trig_bef_del_on_tbl_so_q23374151 before delete on tbl_so_q23374151
for each row begin
set @cnt = if(@cnt is null, 1, (@cnt+1));
/* for cross checking save loop count */
insert into tbl_so_q23374151_rows_affected values ( @cnt );
end;
//
delimiter ;
Testa nu en delete operation :
delete from tbl_so_q23374151 where i like '%1%';
-- now let us see what the loop count was
select @cnt as 'cnt';
+------+
| cnt |
+------+
| 3 |
+------+
Kontrollera nu triggereffekten på huvudtabellen :
-- now let us see the table data
select * from tbl_so_q23374151;
+------+-------+
| i | v |
+------+-------+
| 2 | two |
| 3 | three |
+------+-------+
2 rows in set (0.00 sec)
select count(*) as rows_affected from tbl_so_q23374151_rows_affected;
+---------------+
| rows_affected |
+---------------+
| 3 |
+---------------+
1 row in set (0.00 sec)