塊結構
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:指定在每一次循環中循環變量都會遞減。