PL/SQL总结
1.声明变量以及给变量赋值
--声明变量declare uname varchar2(20); num number;--声明变量赋值declare uname varchar2(20):='admin'; num number:=20;
?
1.1利用表字段类型,给定变量类型
--如果变量类型未知,可利用表名.字段名%type给定declare uname users.name%type; myrow users%rowtype;
?
2.语句块
--begin开始end结束,插入数据declare uname varchar2(20):='admin'; begin insert into info values(uname); end;
?
3.输出信息开启标示
set serveroutput on;
?
4.if语句应用
if 条件 then 代码块elseif 条件 then 代码块(....多个elseif)else 代码块end if;
?
5.case语句应用
--case语句declare num number:=&请输入星期;begin case num when 1 then dbms_output.put_line('星期一'); when 2 then dbms_output.put_line('星期二'); when 3 then dbms_output.put_line('星期三'); when 4 then dbms_output.put_line('星期四'); when 5 then dbms_output.put_line('星期五'); when 6 then dbms_output.put_line('星期六'); when 7 then dbms_output.put_line('星期日'); else dbms_output.put_line('输入出错'); end case;end;
?
6.loop循环
--由于loop循环是死循环,所以跳出循环用exitloop if num>10 then exit; end if;end loop;
?
7.while循环
while 条件 loop 代码块end loop;
?
8.for循环
--for循环只能每次加1,包括20begin for i in 1..20 loop 代码块 end loop;end;
?
9.动态SQL
--returning可以拿到值,并且返回输出--using填充占位符的内容insert into info values (1001,'c');declare plsql varchar2(100):='update info set name=''孙悟空'' where id=:id returning name into :uname'; uname varchar2(100); begin execute immediate plsql using 1001 returning into uname; dbms_output.put_line(uname); end; declare uname varchar2(20); begin execute immediate 'update info set name=''孙悟空'' where id=:id returning name into :uname' using 1001 returning into uname; dbms_output.put_line(uname);end;
?
10.自定义异常处理
--raise手动抛出异常declare n int:=&5; e exception;--定义begin if(n=5) then raise e;--手动抛出 end if; exception--处理 when e then dbms_output.put_line('自定义异常'); when too_many_rows then dbms_output.put_line('查询到多行数据'); when others then dbms_output.put_line('异常');end;
?
11.游标的使用,游标即用于 读取多行数据
--显示游标游标--用显示游标一般分为4步,1.创建 2.打开 3.读取 4.关闭--读取内容使用fetch,相当于结果集读取的Next--loop循环declare cursor my_cursor is select * from info;--声明 myrow info%rowtype; begin open my_cursor;--打开 fetch my_cursor into myrow;--取数据 loop if my_cursor%found then dbms_output.put_line(myrow.id); fetch my_cursor into myrow; else exit; end if; end loop; close my_cursor;--关闭 end;--while循环declare cursor my_cursor is select * from users;--声明 myrow users%rowtype;begin open my_cursor;--打开 fetch my_cursor into myrow;--取数据 while (my_cursor%found) loop dbms_output.put_line(myrow.id||'==='||myrow.name||'==='||myrow.password); fetch my_cursor into myrow; end loop; close my_cursor;--关闭end;--for循环declare cursor my_cursor is select * from users;--声明 myrow users%rowtype;begin for myrow in my_cursor loop dbms_output.put_line(myrow.id||'==='||myrow.name||'==='||myrow.password); end loop;end;
?
12.提示输入,与输出
--输出dbms_output.put_line('输出');--输出前必须打开输出功能set serveroutput on;--输入利用&即可,如果是字符串则需要打上单引号declare uname varchar2(20):='&请输入汉字'; num number:=&请输入数字;
?
13.在oracle中,单引号中使用单引号,则需要利用转义符,转义符为 单引号