Db2 简明教程
DB2 - Triggers
本章介绍触发器,它们的类型以及触发器的创建和放弃。
Introduction
触发器是一组针对数据库中指定表上的 INSERT、UPDATE 或 DELETE 操作进行响应而执行的 actions。触发器一次性存储在数据库中。它们处理数据管理。可以在多个应用程序之间访问和共享它们。使用触发器的优点在于,如果需要在应用程序中进行任何更改,则在触发器处进行,而不是更改访问触发器的每个应用程序。触发器易于维护,且它们迫使应用程序开发更快。触发器使用 SQL 语句 “CREATE TRIGGER” 定义。
Creating a BEFORE trigger
让我们看看如何创建触发器序列:
Syntax:
db2 create sequence <seq_name>
Example :为 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)
Retrieving values from table
让我们看看如何从表中检索值:
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.
Creating an AFTER trigger
让我们看看如何创建 after 触发器:
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.