كل المقررات

الرئيسية / مقرر قاعدة البيانات / الفصل 6 الجزء 1

الفصل 6 (الجزء 1): Triggers and Stored Procedures

Triggers: rules that run by themselves

على طول: الـ trigger هو كود بيشتغل لوحده لما يحصل INSERT أو UPDATE أو DELETE.

فيديو المحاضرة

فيديو المحاضرة

بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.

رسوم متحركة

الـ trigger بيشتغل لوحده

أمثلة SQL

أمثلة قصيرة وبسيطة

الكود قصير والنتيجة اتجرّبت فعلاً. عدّل في المحرر واضغط شغّل.

المثال ١: Trigger بيخصم من الـ stock

Sample output (press Run to produce your own):
item | qty
-----+----
Book | 5  
Pen  | 7  
(2 rows)

المثال ٢: Audit log

Sample output (press Run to produce your own):
acc | old_balance | new_balance
----+-------------+------------
1   | 100         | 80         
(1 row)

المثال ٣: Trigger بيرفض عملية

Sample output (press Run to produce your own):
Error: not enough stock
id | item | qty
---+------+----
2  | Book | 2  
(1 row)

افتح الموضوع المقابل في صفحة LiU TDDD12

اختبار قصير

اختبر فهمك

1. A trigger runs:

2. Which can stop a change before it happens?

3. NEW refers to:

4. A common risk of triggers is:

5. An audit log is a good use of:

تمارين برمجة

جرّب بإيدك

التمرين 1

اعمل trigger بعد DELETE على جدول student بيكتب الاسم المحذوف في جدول deleted_log.

Create an AFTER DELETE trigger on student that writes the deleted name into deleted_log.

(output appears here)

التمرين 2

اعمل BEFORE INSERT trigger يرفض سعر سالب في جدول product.

Create a BEFORE INSERT trigger that rejects a negative price in product.

(output appears here)

مشروع صغير في آخر المحاضرة

مخزن: stock وـ audit بالـ triggers

الداتا: Warehouse sample data: 3 items and 4 sales. Written for this course (our own data, free to reuse).

License / source: Our own sample data; SQLite is in the public domain. Dataset page

الخطوات

  1. الجداول stock وـ sale وـ low_stock_alert جاهزة في الـ starter.
  2. اعمل trigger بعد كل sale يخصم الكمية من stock.
  3. اعمل trigger تاني يكتب في low_stock_alert لما الكمية تنزل تحت 5.
  4. نفّذ المبيعات واعرض الـ alert. المتوقع: Pen بكمية 3 (10 ثم 4 ثم 3) وـ Book مفيش.
Expected output (press Run to produce your own):
item | qty
-----+----
Pen  | 3  
(1 row)
item | qty
-----+----
Book | 17 
Lamp | 5  
Pen  | 3  
(3 rows)

Credits: the topic order follows the lecture list of the course TDDD12 Database Technology at Linköping University (https://www.ida.liu.se/~TDDD12/fo/), whose reading guide is based on the textbook Fundamentals of Database Systems by Elmasri and Navathe. We found no reuse licence on that page, so we link to it and copy nothing from it: the explanations, diagrams, data and code in this lecture are our own. Reference: Elmasri and Navathe, Fundamentals of Database Systems, the sections on triggers and stored procedures.