语法: create [or replace] PROCEDURE过程名(参数列表) AS PLSQL子程序体;
存储过程示例:为指定的职工在原工资的基础上长10%的工资
/* 为指定的职工在原工资的基础上长10%的工资,并打印工资前和工资后的工资 */ SQL> create or replace procedure raiseSalary(empid in number) as pSal emp.sal%type;--保存员工当前 工资 begin --查询该员工的工资 select sal into pSal from emp where empno=empid; --给该员工涨工资 update emp set sal = sal*1.1 where empno=empid; --打印涨工资前后的工资 dbms_output.put_line('员工号:' || empid || '涨工资前 ' || psal || '涨工资后' || psal*1.1); end; 1 /
Procedure created --存储过程调用 --方法一 SQL> set serveroutput on SQL> exec raisesalary(7369);
员工号:7369涨工资前 800涨工资后880
方法二 set serveroutput on begin raisesalary(7369); end; /
CREATE [OR REPLACE] FUNCTION函数名(参数列表) RETURN 函数值类型 AS PLSQL子程序体;
示例:查询某职工的年收入。 SQL> /**/ /* 查询某职工的总收入 */ create or replace function queryEmpSalary(empid in number) return number as pSal number; --定义变量保存员工的工资 pComm number; --定义变量保存员工的奖金 begin select sal,comm into psal,pcomm from emp where empno = empid; return psal*12+nvl(pcomm,0); end; /
示例1:限制非工作时间向数据库插入数据 SQL> create or replace trigger securityEmp before insert on emp declare begin if to_char(sysdate,'day')in('星期四','星期六','星期日') or to_number(to_char(sysdate,'hh24'))not between 8 and 18 then raise_application_error(-20001,'不能在非工作时间插入数据。'); end if; end; /
Trigger created
触发语句与伪记录变量的值 触发语句 :old :new Insert 所有字段都是空(null) 将要插入的数据 Update 更新以前该行的值 更新后的值 delete 删除以前该行的值 所有字段都是空(null) 示例2:确认数据(检查emp表中sal的修改值不低于原值) SQL> create or replace trigger checkSal before update of sal on emp for each row declare begin if :new.sal<:old.sal then raise_application_error(-20001,'更新后的薪水比更新前小'); end if; end; /
Trigger created 运行后结果: SQL> update emp set sal=260 where empno=7499;
update emp set sal=260 where empno=7499
ORA-20001: 更新后的薪水比更新前小 ORA-06512: 在 "SCOTT.CHECKSAL", line 4 ORA-04088: 触发器 'SCOTT.CHECKSAL'执行过程中出错