DB2 - ทริกเกอร์
บทนี้อธิบายถึงทริกเกอร์ประเภทการสร้างและการลดลงของทริกเกอร์
บทนำ
ทริกเกอร์คือชุดของการดำเนินการซึ่งดำเนินการเพื่อตอบสนองต่อการดำเนินการ INSERT, UPDATE หรือ DELETE บนตารางที่ระบุในฐานข้อมูล ทริกเกอร์จะถูกเก็บไว้ในฐานข้อมูลพร้อมกัน พวกเขาจัดการกับการกำกับดูแลข้อมูล สามารถเข้าถึงและแชร์ระหว่างแอพพลิเคชั่นต่างๆ ข้อดีของการใช้ทริกเกอร์คือหากจำเป็นต้องทำการเปลี่ยนแปลงใด ๆ ในแอปพลิเคชันจะดำเนินการที่ทริกเกอร์ แทนที่จะเปลี่ยนแต่ละแอปพลิเคชันที่เข้าถึงทริกเกอร์ ทริกเกอร์ดูแลรักษาง่ายและบังคับให้พัฒนาแอปพลิเคชันได้เร็วขึ้น ทริกเกอร์ถูกกำหนดโดยใช้คำสั่ง SQL“ CREATE TRIGGER”
ประเภทของทริกเกอร์
ทริกเกอร์มีสองประเภท:
1. ก่อนทริกเกอร์
พวกเขาจะดำเนินการก่อนการดำเนินการ SQL ใด ๆ
2. หลังจากทริกเกอร์
พวกเขาจะดำเนินการหลังจากการดำเนินการ SQL
การสร้างทริกเกอร์ก่อน
ให้เราดูวิธีสร้างลำดับของทริกเกอร์:
Syntax:
db2 create sequence <seq_name> 
    Example: การสร้างลำดับของทริกเกอร์สำหรับ table shopper.sales1
db2 create sequence sales1_seq as int start with 1 increment by 1 
    Syntax:
db2 create trigger <trigger_name> no cascade before insert on 
<table_name> referencing new as <table_object> for each row set 
<table_object>.<col_name>=nextval for <sequence_name> 
    Example: การสร้างทริกเกอร์สำหรับตาราง shopper.sales1 เพื่อแทรกหมายเลขคีย์หลักโดยอัตโนมัติ
db2 create trigger sales1_trigger no cascade before insert on 
shopper.sales1 referencing new as obj for each row set 
obj.id=nextval for sales1_seq 
    ตอนนี้ลองแทรกค่าใด ๆ :
db2 insert into shopper.sales1(itemname, qty, price) 
values('bicks', 100, 24.00) 
    การดึงค่าจากตาราง
ให้เราดูวิธีการดึงค่าจากตาราง:
Syntax:
db2 select * from <tablename> 
    Example:
db2 select * from shopper.sales1 
    Output:
ID       ITEMNAME       QTY 
-------  ------------   ---------- 
    3      bicks            100 
    2      bread            100 
  
  2 record(s) selected. 
    สร้าง AFTER ทริกเกอร์
ให้เราดูวิธีสร้าง after trigger:
Syntax:
db2 create trigger <trigger_name> no cascade before insert on 
<table_name> referencing new as <table_object> for each row set
 <table_object>.<col_name>=nextval for <sequence_name> 
    Example: [เพื่อแทรกและดึงค่า]
db2 create trigger sales1_tri_after after insert on shopper.sales1 
for each row mode db2sql begin atomic update shopper.sales1 
set price=qty*price; end 
    Output:
//inseting values in shopper.sales1 
db2 insert into shopper.sales1(itemname,qty,price) 
values('chiken',100,124.00) 
//output 
ID    ITEMNAME       QTY         PRICE 
----- -------------- ----------- -----------                      
    3 bicks          100         2400.00 
    4 chiken         100         12400.00 
    2 bread          100         2400.00 
	3 record(s) selected. 
    วางทริกเกอร์
นี่คือวิธีที่ทริกเกอร์ฐานข้อมูลหลุด:
Syntax:
db2 drop trigger <trigger_name> 
    Example:
db2 drop trigger slaes1_trigger