---
title: "PL/SQL语言学习"
author: "goby2008"
date: "2009-06-01T23:11:41Z"
tags: ["SQL"]
slug: "pl-sql"
draft: false
lastmod: "2009-06-02T16:10:04Z"
id: 399957
url: "https://goby2008.iteye.com/blog/399957"
---

PL/SQL语言学习  
**变量声明**  
1、变量声明的内容  
   赋予变量适当名称  
   赋予变量正确的数据类型  
   定义变量（标准、记录）  
   控制变量范围  
2、命名规则  
   变量由字符开头  
   可以包含：数字，下划线、“$”，“#”等  
   变量长度范围：1~30  
   大小写不区分  
   变量名不能是系统关键字.  
set serveroutput on size 10000  
**例子一：**  
declare  
x varchar2(10);  
begin  
x:='this is ...';  
dbms\_output.put\_line('x的值为：'||x);  
end;  
/

执行

/

**例子2：**  
set serveroutput on size 10000  
declare  
x varchar2(10):='abcd';  
y INTEGER:=123;  
begin  
x:='this is ...';  
dbms\_output.put\_line('x的值为：'||x||'Y的值为：'||y);  
end;  
/

**例子3:**

declare  
a number;  
b varchar2(10);  
begin  
a:=2;  
if a=1 then  
b:='A';  
elsif a=2 then  
b:='b';  
else  
b:='c';  
end if;  
dbms\_output.put\_line('b等于'||b);  
end;  
/

**例子4：**

declare  
a number;  
b varchar2(10);  
begin  
a:=2;  
case  
when a=1 then b:='A';  
when a=2 then b:='B';  
else  
b:='others';  
end case;  
dbms\_output.put\_line('b等于'||b);  
end;  
/

 

**循环语句**

1、基本循环(LOOP)  
   LOOP  
   ...  
   END LOOP  
2、WHILE循环  
   WHILE expresstion LOOP  
   ...  
   END LOOP;  
3、FOR循环  
   FOR counter IN\[REVERSE] start\_value...end\_value LOOP  
   ...  
   END LOOP;

 

**![](/images/smiles/icon_arrow.gif)例子1：**  
declare  
x number;  
begin  
x:=0;  
LOOP  
x:=x+1;  
IF x&gt;3  THEN  
EXIT IF;  
DBMS\_OUTPUT.PUT\_LINE('内：x='||X);  
END LOOP;  
DBMS\_OUTPUT.PUT\_LINE('外：x='||X);  
END;  
/

 

**例子2：**  
declare  
x number;  
begin  
x:=0;  
LOOP  
x:=x+1;  
EXIT WHEN x&gt;=3;  
DBMS\_OUTPUT.PUT\_LINE('内：x='||X);  
END LOOP;  
DBMS\_OUTPUT.PUT\_LINE('外：x='||X);  
END;  
/

**例子3：**  
declare  
x number;  
BEGIN  
x:=0;  
WHILE x&lt;=3 LOOP  
x:=x+1;  
DBMS\_OUTPUT.PUT\_LINE('内：x='||x);  
END LOOP;  
DBMS\_OUTPUT.PUT\_LINE('外：x='||x);  
END;  
/  
**例子4:**  
begin  
for i in 1..5 loop  
dbms\_output.put\_line('i='||i);  
end loop;  
dbms\_output.put\_line(' end of for loop');  
end;  
/  
**例子5: 反循环**  
begin  
for i in reverse 1..5 loop  
dbms\_output.put\_line('i='||i);  
end loop;  
dbms\_output.put\_line(' end of for loop');  
end;  
/

**例子6：goto**  
declare  
x number;  
begin  
x:=0;  
&lt;&lt;repeat\_loop&gt;&gt;  
x:=x+1;  
dbms\_output.put\_line(x):  
if x&lt;3 then  
goto repeat\_loop;  
end if;  
end;  
/