存储过程和函数
存储过程和函数的区别:
函数必须通过ruturn 关键字返回一个值
存储过程不需要return 返回一个值
语法:
create or replace procedure 存储过程名 as/is
create or replace function 函数名 return 返回类型 as/is
什么时候用存储过程,什么时候用函数:
一般来说,当只有一个返回值的时候用函数,
当没有返回值或需要多个返回值的时候用存储函数
引用型变量和记录型变量
Declare
i Number;
a student.sname%Type;--引用型变量
b student%Rowtype;--记录型变量(b,可以看成是一个对象)
Begin
i :=107;
Select s.sname Into a From student s Where s.sno=i;
dbms_output.put_line('查询出的a:'||a);
--Select * Into b From student s Where s.sno=i;
--dbms_output.put_line('查询出的b:'||b.sname);
End;
游标
--游标
/*
isopen --游标是否打开
notfound --是否有下一个
found
rowcount --已经取出的记录的行数
*/
Declare
stu student%Rowtype;
Cursor stus Is Select * From student;
Begin
Open stus;
Loop --循环
Fetch stus Into stu; --遍历,给一个变量
Exit When stus%Notfound; --退出条件
dbms_output.put_line(stu.sname);
End Loop;
Close stus;
End;
循环遍历
Create Or Replace Procedure hanqi(scla In Number) As
--游标
Cursor stus Is Select * From student s Where s.class=scla;
stu student%Rowtype;
Begin
Open stus;
Loop --循环
Fetch stus Into stu; --遍历
Exit When stus%Notfound; --退出条件
dbms_output.put_line(stu.name);
End Loop;
Close stus;
End;
Create Or Replace Procedure hanqi2(scla In Number,vari Out number) As
Begin
Update student s Set s.ssex='女' Where s.class = scla;
dbms_output.put_line('记录已经修改!');
Select Count(*) Into vari From student s Where s.class = scla;
End;
存储函数
--存储函数
Create Or Replace Function cal_add(a In number,b In Number)
As
c Number;
Begin
c := a+b;
Return c;
End;