##1.最简单的plsql
例子:
declare --开始
x varchar2(10); --声明变量
begin --开始标识
x:='This is ..'; --给变量赋值
dbms_output.put_line('x的值为:'||x); --输出x的值
end; --结束标识
/
在plsql中用||连接两个字符 等于java中的+符号
设置服务器的plsql显示结果
set serveroutput on size 1000;
--或直接写:
set serveroutput on;
再执行/ 可以看到这个结果 x的值为: This is ..
dbms_output.put_line('x的值为:'||x); 等同于 dbms_output.put('x的值为:'||x); dbms_output.new_Line;
##2.分支语句
###1.if分支
If… then
Elsif … then
Else …
End if
例子1:
declare
a number:=3;
b number;
begin
if a<3 then b:=1;
elsif a>3 then b:=5;
else b:=3;
end if;
dbms_output.put_line(b);
end;
/
例子2:
declare
a number;
b varchar2(10);
begin
a:=4;
if a=1 then b:='a';
elsif a=2 then b:='b';
else b:='c';
end if;
dbms_output.put_line(b); --输出结果为:c
end;
/
###2.case分支
Case
When … then …
Else
End case
例子:
declare
a number;
b varchar2(10);
begin
a:=2;
case
when a=1 then b:='a';
when a=2 then b:='b';
when a=3 then b:='c';
else b:='others';
end case;
dbms_output.put_line(b);
end;
/
##3.循环语句
###1.基本循环(loop)
Loop … end loop
示例1:
declare
x number ;
begin
x:=0;
loop
x:=x+1;
if x>5 then
exit;
end if;
dbms_output.put_line('内x='|| x);
end loop;
dbms_output.put_line('外x='|| x);
end;
/
/*结果
内x=1 内x=2 内x=3
内x=4 内x=5 外x=6
*/
示例2:
declare
x number;
begin
x:=0;
loop
x:=x+1;
exit when x>=3; --当x大于等于3的时候跳出
dbms_output.put_line('内x='|| x);
end loop;
dbms_output.put_line('外x='||x);
end ;
/
/*结果
内x=1
内x=2
外x=3
*/
###2.while循环
While expression loop… end loop;
示例1:
declare
x number;
begin
x:=0;
while x<=3 loop
x:=x+1;
dbms_output.put_line('内x='||x);
end loop;
dbms_output.put_line('外x='||x);
end;
/
示例2:
declare
x number;
begin
x:=0;
while x<=6 loop
x:=x+1;
dbms_output.put_line('内x='||x);
exit when x=3; --满足条件跳出循环
end loop;
dbms_output.put_line('外x='||x);
end;
/
###3.for循环
For counter in [reverse] start_value..end_value loop
…
End loop;
示例1:
begin
for i in 1..6 loop
dbms_output.put_line('i='|| i);
end loop;
dbms_output.put_line('end of for loop');
end;
/
/*结果
i=1
i=2
i=3
i=4
i=5
i=6
end of for loop
*/
示例2:
begin
for i in reverse 1..5 loop
dbms_output.put_line(i);
end loop;
end;
/
/*结果
5
4
3
2
1
*/
###4.Goto的使用
declare
x number;
begin
x:=0;
<<repeat_loop>>
x:=x+1;
dbms_output.put_line(x);
if x<3 then
goto repeat_loop;
end if;
end;
/
/*结果
1
2
3
*/
4.异常处理
Exception when .. then ..
示例1:
declare
test varchar2(10);
begin
select ename into test from emp where empno=55;
dbms_output.put_line(test);
exception
when No_DATA_FOUND then
dbms_output.put_line('没有找到数据');
end;
/
示例2:
declare
test varchar2(10);
begin
select ename into test from emp ;
dbms_output.put_line(test);
exception
when no_data_found then
dbms_output.put_line('没有找到数据!');
when too_many_rows then
dbms_output.put_line('返回的数据行太多!');
when others then
dbms_output.put_line('其他问题!');
end;
/
示例3:
declare
ename varchar2(10);
begin
select ename into ename from emp where empno=33;
exception
when others then
dbms_output.put_line('出错了!');
end;
/