ORACLE的基础SQL(四)

—存储过程
–存储过程:存储过程就是提前已经编译好的一段pl/sql语言,放置在数据库端
——–可以直接被调用。这一段pl/sql一般都是固定步骤的业务。
—-给指定员工涨100块钱
create or replace procedure p1(eno emp.empno%type)
is

begin
update emp set sal=sal+100 where empno = eno;
commit;
end;

select * from emp where empno = 7788;
—-测试p1
declare

begin
p1(7788);
end;

—-通过存储函数实现计算指定员工的年薪
—-存储过程和存储函数的参数都不能带长度
—-存储函数的返回值类型不能带长度
create or replace function f_yearsal( eno emp.empno%type) return number
is
s number(10);
begin
select sal*12+nvl(comm, 0) into s from emp where empno = eno;
return s;
end;

—-测试f_yearsal
—-存储函数在调用的时候,返回值需要接收。
declare
s number(10);
begin
s := f_yearsal(7788);
dbms_output.put_line(s);
end;

—out类型参数如何使用
—使用存储过程来算年薪
create or replace procedure p_yearsal(eno emp.empno%type, yearsal out number)
is
s number(10);
c emp.comm%type;
begin
select sal*12, nvl(comm, 0) into s, c from emp where empno = eno;
yearsal := s+c;
end;

—测试p_yearsal
declare
yearsal number(10);
begin
p_yearsal(7788, yearsal);
dbms_output.put_line(yearsal);
end;

—-我们可以使用存储函数有返回值的特性,来自定义函数。
—-而存储过程不能用来自定义函数。
—-案例需求:查询出员工姓名,员工所在部门名称。
—-案例准备工作:把scott用户下的dept表复制到当前用户下。
create table dept as select * from scott.dept;
—-使用传统方式来实现案例需求
select e.ename, d.dname
from emp e, dept d
where e.deptno=d.deptno;
—-使用存储函数来实现提供一个部门编号,输出一个部门名称。
create or replace function fdna(dno dept.deptno%type) return dept.dname%type
is
dna dept.dname%type;
begin
select dname into dna from dept where deptno = dno;
return dna;
end;
—使用fdna存储函数来实现案例需求:查询出员工姓名,员工所在部门名称。
select e.ename, fdna(e.deptno)
from emp e;

—触发器,就是制定一个规则,在我们做增删改操作的时候,
—-只要满足该规则,自动触发,无需调用。
—-语句级触发器:不包含有for each row的触发器。
—-行级触发器:包含有for each row的就是行级触发器。
———–加for each row是为了使用:old或者:new对象或者一行记录。

—语句级触发器
—-插入一条记录,输出一个新员工入职
create or replace trigger t1
after
insert
on person
declare

begin
dbms_output.put_line(‘一个新员工入职’);
end;
—触发t1
insert into person values (1, ‘小红’);
commit;
select * from person;

—行级别触发器
—不能给员工降薪
—raise_application_error(-20001~-20999之间, ‘错误提示信息’);
create or replace trigger t2
before
update
on emp
for each row
declare

begin
if :old.sal>:new.sal then
raise_application_error(-20001, ‘不能给员工降薪’);
end if;
end;
—-触发t2
select * from emp where empno = 7788;
update emp set sal=sal-1 where empno = 7788;
commit;

—-触发器实现主键自增。【行级触发器】
—分析:在用户做插入操作的之前,拿到即将插入的数据,
——给该数据中的主键列赋值。
create or replace trigger auid
before
insert
on person
for each row
declare

begin
select s_person.nextval into :new.pid from dual;
end;
–查询person表数据
select * from person;
—使用auid实现主键自增
insert into person (pname) values (‘a’);
commit;
insert into person values (1, ‘b’);
commit;

猜你喜欢

转载自blog.csdn.net/jimbo_chou/article/details/82557373
今日推荐