Oracle10G学习笔记之四Pl/sql基础

来源:互联网 发布:吴彦祖颜值巅峰知乎 编辑:程序博客网 时间:2024/05/28 23:10

eg1:
/*基本Pl/sql语句块*/
declare
x varchar2(20);
/*
数据类型可以为number、integer、string(10)
可以定义时赋值,x number:=123;x string(20):='string';
*/
begin
--行注释
/*
块注释。
默认不输出。设置: set serveroutput on size 10000
*/
x:='This is ...';
dbms_output.put_line('x的值为'||x);
end;
/

eg2:
/*if语句块*/
declare
age number;
old varchar2(50);
begin
age:=18;
if age>18 then
old:='am adult';
elsif age<18 then
old:='am not adult';
else
old:='am 18 years old';
end if;
dbms_output.put_line('I '||old);
end;
/

eg3:
/*case语句块*/
declare
age number;
old varchar2(50);
begin
case
when age<18 then old:='am adult';
when age>18 then old:='am not adult';
else
old:='am 18 years old';
end case;
dbms_output.put_line('I '||old);
end;
/

eg4:
/*loop语句块*/
declare
x number:=0;
begin
loop
x:=x+1;
if x>=3 then
exit;
end if;
dbms_output.put_line('循环体内:x='||x);
end loop;
dbms_output.put_line('循环体外:x='||x);
end;
/

eg5:
/*loop语句块2*/
declare
x number:=0;
begin
loop
x:=x+1;
exit when x>=3;
dbms_output.put_line('循环体内:x='||x);
end loop;
dbms_output.put_line('循环体外:x='||x);
end;
/

eg6:
/*while语句块*/
declare
x number:=0;
begin
while x<3 loop
x:=x+1;
dbms_output.put_line('循环体内:x='||x);
end loop;
dbms_output.put_line('循环体外:x='||x);
end;
/

eg7:
/*for语句块*/
declare
x number:=0;
begin
for x in 1..5 loop
dbms_output.put_line('循环体内:x='||x);
end loop;
dbms_output.put_line('循环体外:x='||x);
end;
/

eg8:
/*for语句块2*/
declare
x number:=0;
begin
for x in reverse 1..5 loop
dbms_output.put_line('循环体内:x='||x);
end loop;
dbms_output.put_line('循环体外:x='||x);
end;
/

eg9:
/*goto语句块实现循环*/
declare
x number:=0;
begin
<<repeat_loop>>
x:=x+1;
dbms_output.put_line('x='||x);
if x<3 then
goto repeat_loop;
end if;
end;
/

eg10:
/*异常处理*/
/*
常见系统异常
dup_val_on_index  向有唯一约束的表中插入重复行
no_data_found   在一个select into语句中无返回值
too_many_rows   select into语句返回了多行
value_error    一个算法、转换、截断或大小约束发生错误
zero_divide   发生被零除
*/
declare
begin
dbms_output.put_line(1/0);
exception
when zero_divide then
dbms_output.put_line('零不能被除!');
end;
/

eg11:
/*自定义异常*/
declare
myexception  exception;
begin
if 3>2 then
raise myexception;
end if;
exception
when myexception then
dbms_output.put_line('我的自定义异常!');
end;
/

eg12:
/*
记录是由几个相关值构成的复合变量,常用于支持select语句的返回值。
使用记录可以将一行数据看成一个单元进行处理,而不必将每一列单独处理。
*/
declare
type myrecord is record(
id NUMBER(4),
name emp.ename%type);
real_record myrecord;
begin
select EMPNO,ENAME into real_record from emp where EMPNO=7900;
dbms_output.put_line(real_record.id||'   '||real_record.name);
end;
/

eg12:
/*行结构复制记录*/
declare
myrecord emp%rowtype;
begin
select * into myrecord from emp where EMPNO=7900;
dbms_output.put_line(myrecord.empno||'   '||myrecord.ename||'   '||myrecord.job);
end;
/

原创粉丝点击