PL/SQL程序设计
下面通过三个例子分别实现存储过程的创建、函数的创建以及触发器的创建
- 创建一个存储过程,输出不同类型图书的数量、平均价格。
create or replace procedure books_msg
as
books_count orderitem.quantity%type;
begin
for emp in (
select title,ISBN,cost from books
)
loop
select sum(quantity) into books_count from orderitem where ISBN=emp.ISBN;
dbms_output.put_line(emp.title||' 单价:'||emp.cost||' 数量:'||books_count);
end loop;
end books_msg;
***注意:在输入完创建代码后需要输入"/"后按回车完成创建,下面同理
调用:
- 创建一个函数,以客户号为参数,返回该客户订购图书的价格总额。
create or replace function sumprice(
id customers.customer_id%type)
return books.cost%type
as
sumprice books.cost%type;
begin
select sum(quantity*cost) into sumprice from customers,books,orders,orderitem
where customers.customer_id = orders.customer_id and orders.order_id = orderitem.order_id and orderitem.isbn = books.isbn and customers.customer_id = id;
return sumprice;
exception
when no_data_found then
dbms_output.put_line('the id is invaild!');
end sumprice;
调用:
- 创建一个触发器,禁止客户在非工作时间(早上8:00之前,晚上17:00之后)下订单。
CREATE OR REPLACE TRIGGER trg_orderitem
BEFORE INSERT OR UPDATE OR DELETE ON orderitem
BEGIN
IF TO_CHAR(SYSDATE,'HH24:MI') NOT BETWEEN '08:00' AND '17:00'
OR TO_CHAR(SYSDATE,'DY','NLS_DATE_LANGUAGE=AMERICAN') IN ('SAT','SUN')
THEN
RAISE_APPLICATION_ERROR(-20005,'只能在正常的时间内进行改变。');
END IF;
END trg_orderitem;
验证: