PL/SQL高级应用
1、游标,对结果集进行逐条处理,分为显示和隐式游标
游标的属性:%FOUND,%ISOPEN,%NOTFOUND,%ROWCOUNT
显式游标的使用方法:
1 declare
2 cursor mycur is
3 select * from books;
4 myrecord books%rowtype;
5 begin
6 open mycur;--打开游标
7 fetch mycur into myrecord;--表的第一条
8 while mycur%found loop
9 dbms_output.put_line(myrecord.books_id||','|| myrecord.books_name || ','|| myrecord.pub);
10 fetch mycur into myrecord;
11 end loop;
12 close mycur;--关闭游标
13* end;
使用游标参数,游标的参数只给出类型,不给出大小
declare
2 cursor cur_para(id varchar2) is
3 select books_name from books where books_id =id;
4 t_name books.books_name%type;--定义变量
5 begin
6 OPEN cur_para('0001');
7 loop
8 FETCH cur_para INTO t_name;
9 EXIT WHEN cur_para%NOTFOUND;
判断是否打开游标
1 DECLARE
2 t_name books.books_name%TYPE;
3 CURSOR cur(id varchar2) IS
4 SELECT books_name FROM books WHERE books_id>id;
5 BEGIN
6 if cur%ISOPEN THEN
7 DBMS_OUTPUT.PUT_LINE('游标已经打开');
8 ELSE
9 OPEN cur('0001');
10 END IF;
11 FETCH cur INTO t_name;--将结果放进变量
12 CLOSE cur;
13 DBMS_OUTPUT.PUT_LINE(t_name);
14* END;
定义变量数量和取出数量一定要一致
判断游标中结果的数量
1 DECLARE
2 t_name varchar2(40);
3 CURSOR mycur IS
4 SELECT books_name FROM books;
5 BEGIN
6 OPEN mycur;
7 LOOP
8 FETCH mycur INTO t_name;
9 EXIT WHEN mycur%NOTFOUND OR mycur%NOTFOUND IS NULL;
10 DBMS_OUTPUT.PUT_LINE('记录数为:'|| mycur%ROWCOUNT);
11 END LOOP;
12 CLOSE mycur;
13* END;
10 dbms_output.put_line(t_name);
11 end loop;
12 CLOSE cur_para;
13 END;
14 /
另外一种使用参数
DECLARE
2 CURSOR cur_para(id varchar2) IS
3 SELECT books_name FROM books where books_id=id;
4 BEGIN
5 DBMS_OUTPUT.PUT_LINE('***************结果集为:********');
6 FOR cur in cur_para('0001' ) LOOP
7 DBMS_OUTPUT.PUT_LINE(cur.books_name);
8 END LOOP;
9 END;
10 /
使用游标更新数据
1 DECLARE
2 CURSOR cur IS
3 SELECT books_name FROM books FOR UPDATE;
4 text varchar2(40);
5 BEGIN
6 OPEN cur;
7 FETCH cur INTO text;
8 WHILE cur%FOUND LOOP
9 UPDATE books SET books_name=books_name|| '_t' WHERE books_name=text;
10 FETCH cur INTO text;
11 END LOOP;
12 CLOSE cur;
13 END;
隐式游标:
1 BEGIN
2 FOR cur IN(SELECT dname FROM dept) LOOP
3 DBMS_OUTPUT.PUT_LINE(cur.dname);
4 END LOOP;
5* END;
存储过程
语法:CREATE [OR REPLACE] PROCEDURE 名称
[(param1 [{IN|OUT | INOUT}])] param1_type
[(param2 [{IN|OUT | INOUT}])] param2_type
IS|AS
BEGIN
Proc_body;
END;
如果编译有错误,使用SHOW ERRORS PROCEDURE XXX查看错误
第一个例程
1 CREATE OR REPLACE PROCEDURE myproc(id IN varchar2)
2 IS
3 name varchar2(100);
4 BEGIN
5 SELECT books_name INTO name FROM books WHERE books_id=id;
6 DBMS_OUTPUT.PUT_LINE(name);
7* END myproc;
如何调用myproc
1 DECLARE
2 tid varchar2(10);
3 BEGIN
4 tid:='0002';
5 myproc(tid);
6* END;
传人一个参数给myproc
如果不传入参数,可以直接使用
DECLARE
BEGIN
XXX
END;
或者直接使用execcute 过程名称(参数);过程名称和参数中间不能有空格!!
定义有输入参数和输出参数的过程
create or replace
PROCEDURE myproc2(id IN varchar2,name OUT varchar2)
IS
BEGIN
SELECT books_name INTO name FROM books WHERE books_id=id;
END;
调用有两个参数的过程
>DECLARE
2 tid varchar2(10);
3 tname varchar(40);
4 BEGIN
5 tid:='0001';
6 myproc2(tid,tname);
7 DBMS_OUTPUT.PUT_LINE(tname);
8 END;
阅读(766) | 评论(0) | 转发(0) |