6oracle实验六指导书 下载本文

内容发布更新时间 : 2024/5/5 16:50:04星期一 下面是文章的全部内容请认真阅读。

实验六 PL/SQL基本语句

【实验目的】

(1) 掌握PL/SQL基本语法

(2) 练习PL/SQL数据定义及使用 (3) 掌握PL/SQL程序结构

【实验原理】

(1) PL/SQL的程序结构

DECLARE --标记声明部分

…… --此处用来定义常量、变量、类型和游标等(可选) BEGIN --标记程序主体部分开始

…… --此处用来编写各种PL/SQL语句、函数和存储过程 EXCEPTION --标记异常处理部分开始

…… --此处用来编写异常处理代码(可选) END; --标记程序主体部分结束

(2) 声明变量

<变量名> <数据类型> [(宽度) := <初始值>];

(3) 数据控制语句

(a) 选择语句

? If判断

if condition then Statement end if

if condition then Statements_1 else Statements_2 end if if condition1 then Statements_1

elsif condition2 then Statements_2 else Statements_3 end if ? CASE语句

Case 变量

WHEN表达式1 then值1 WHEN表达式2 then值2 WHEN表达式3 then值3 WHEN表达式4 then值4 【ELSE值5】 END ;

(b) 循环语句

? loop…exit…end loop循环控制语句 ? loop..exit when..end loop循环控制 ? WHILE…..LOOP…END LOOP循环控制语句 ? FOR..IN..LOOP…END LOOP循环控制语句

(4) 输出语句

(a) 设置环境变量,打开输出缓冲区:SET SERVEROUTPUT ON (b) 输出语句:DBMS_OUTPUT.PUT_LINE(str)

【实验示例】

1. 从scott方案下的emp表中查询编号为7788的员工的工资,如果工资小于500,将其

乘以1.5;如果工资小于1500,将其乘以1.3;如果工资小于3000,将其乘以1.1;否则将工资乘以1.0。 Set serveroutput on; declare

v_sal scott.emp.sal%type; begin

select sal into v_sal from scott.emp where empno=7788; if v_sal<500 then

update scott.emp set sal=sal*1.5 where empno=7788; elsif v_sal<1500 then

update scott.emp set sal=sal*1.3 where empno=7788; elsif v_sal<3000 then

update scott.emp set sal=sal*1.1 where empno=7788; else

update scott.emp set sal=sal*1.0 where empno=7788; end if; commit; end; / 2. 举例说明处理系统预定义的错误。当执行select语句时,如果没有找到empno=7788

的记录,则发生no_data_found错误,如果找到多条empno=7788的记录,则发生too_many_rows错误。No_data_found和too_many_rows错误直接在exception的when从句处理。 Declare

V_comm scott.emp.comm%type; Begin

Select comm into v_comm from scott.emp where empno=7788; Exception

When no_data_found then

Dbms_output.put_line('no data!'); When too_many_rows then

Dbms_output.put_line( 'too_many_rows!'); When others then Null; End; /

3. 用case语句判断grade变量的值,当grade等于’A’时,输出excellent;当grade等

于’B’时,输出very good;当grade等于’C’时,输出good;当grade等于’D’时,输出fair;当grade等于’F’时,输出poor;否则输出no such grade。 Declare

grade char(20):='B'; begin

Case grade

When 'A' then dbms_output.put_line('excellent'); When 'B' then dbms_output.put_line('very good'); When 'C' then dbms_output.put_line('good'); When 'D' then dbms_output.put_line('fair'); When 'F' then dbms_output.put_line('poor'); Else dbms_output.put_line('no such grade'); End case; End; /

4. Declare

number integer:=2; begin

Case number

WHEN 1 then dbms_output.put_line('number的值:'||number); WHEN 2 then dbms_output.put_line('number的值:'||number); WHEN 3 then dbms_output.put_line('number的值:'||number); WHEN 4 then dbms_output.put_line('number的值:'||number); ELSE dbms_output.put_line('Invalid Option.'); END case; end; /

5.

(1) declare

number1 integer:=80; number2 integer:=90; i integer:=0; begin loop

number1:=number1+1; if number1=number2 then exit; else

i:=i+1; end if; end loop;

dbms_output.put_line('共循环次数:'||to_char(i)); end; /

(2) declare