块结构
PL/SQL块以正斜杠(/)结尾
例子:
--set serveroutput on --打开服务器输出,因为我是使用PL/SQL Developer,所以不需要这一行
declare
v_width integer;
v_height integer := 2;
v_area integer := 6;
begin
-- set the width equal to the area divided by the height
v_width := v_area / v_height;
dbms_output.put_line('v_width = ' || v_width);
exception
when zero_divide then
dbms_output.put_line('Division by zero');
end;
/
结果:
v_width = 3
变量和类型
在declare中声明变量:
例如:
v_width integer;
%TYPE关键字:
也可以通过%TYPE来定义变量的类型,这个关键字使用表中指定列相同的类型。
例如:这个变量的类型与test 表中的id类类型相同。
v_id test.id%TYPE;
条件逻辑例子:
declare
v_message varchar2(100) ;
v_count integer := 1;
begin
if v_count > 0 then
v_message := 'v_count is postitive';
dbms_output.put_line(v_message);
elsif v_count = 0 then
v_message := 'v_count is zero';
dbms_output.put_line(v_message);
else v_message := 'v_count is negative';
dbms_output.put_line(v_message);
end if;
end;
结果:
v_count is postitive
循环
简单循环:直到显式结束循环之前一直运行。
while循环:知道某个特定条件出现之前一直运行。
for循环:运行预先确定的次数
1.简单循环语法:
LOOP statements END LOOP;
EXIT WHEN语句在指定条件出现时结束循环。
例如 :
declare v_count integer := 0;
begin
loop v_count := v_count + 1;
dbms_output.put_line('v_count = ' || v_count);
EXIT WHEN v_count = 5;
end loop;
end;
结果:
v_count = 1
v_count = 2
v_count = 3
v_count = 4
v_count = 5
continue或 continue when语句结束循环的当前迭代。
declare v_count integer := 0;
begin
loop -- after the continue statement is executed, control
returns here v_count := v_count + 1;
if v_count = 3 then continue;
end if;
dbms_output.put_line('v_count = ' || v_count);
EXIT WHEN v_count = 5;
end loop;
end;
结果:
v_count = 1
v_count = 2
v_count = 4
v_count = 5
2.while循环
declare v_count integer := 0;
begin
while v_count < 3 loop
v_count := v_count + 1;
dbms_output.put_line('v_count = ' || v_count);
end loop;
end;
结果:
v_count = 1
v_count = 2
v_count = 3
4.for循环
begin
for v_count in 1..3 loop
dbms_output.put_line('v_count = ' || v_count);
end loop;
end;
结果:
v_count = 1
v_count = 2
v_count = 3
v_count:没有进行显示声明,for循环在这种情况下会自动创建一个integer变量。
begin
for v_count in reverse 1..3 loop
dbms_output.put_line('v_count = ' || v_count);
end loop;
end;
结果:
v_count = 3
v_count = 2
v_count = 1
reverse:指定在每一次循环中循环变量都会递减。