简体   繁体   中英

SQL: Statement Triggers VS For Each Row

EDIT: I don't know what distro it is, it's in an exam paper.

I'm just not getting this, sadly. I'm quite happy with Row level triggers but could someone explain to me how the results would differ if the trigger was statement level instead?

Relation/Statement Trigger/Row Level Trigger

Employee(ID VARCHAR2(30), Salary NUMBER)


Create Trigger AutoRaise
After insert on Employee
Referencing new table as NT
update Employee
Set salary = salary + (select avg(salary) from NT)


Create trigger AutoRaise
After insert on Employee
Referencing new table as NT
For each Row
Update employee
Set salary = salary + (select avg(salary) from NT)

I understand that in the for each row trigger it'll fire for each row affected by the triggering statement. Now would the statement level trigger modify the results differently? Say if I inserted five tuples in one statement, would it set the salary etc for them all? If so, what's the benefit of the row level trigger here?

I've tried searching but I just can't get my head around it.

Thanks,

EDIT: Now, I'm just being dense but would either trigger produce different outputs? For the statement level trigger if I used the example values:

In table before trigger's creation:

(A,50)

Added in ONE statement after trigger is created:

(B,70), (C,30)

The first trigger would set the salary for each tuple being inserted, surely? So the first would become 120 (as the average is 50, 70 + 50 = 120) and the second would become 80. If this is true, how does the second trigger differ in results?

The difference is that in case of statement level trigger SELECT avg(salary) FROM NT will return average of salary for inserted rows, but in case of row level, avg(salary) always equals to salary of new record (trigger executed for each row individually). Also, statement level trigger will be executed if no records affected. In case of row level trigger most RDMS don't fire it when 0 records affected.

Side note. I believe the trigger bodies in the question are given for example only; otherwise, I'd recommend not using recursion in triggers even if particular RDMS has such an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM