//PS:SET SERVEROUTPUT ON;
//DBMS_OUTPUT.PUT_LINE();--输出
--实现操控程序处理的细节过程
PL/SQL程序以块(BLOCK)为基本单位,分三部分:声明部分(用declare开头)、执行部分(以begin开头)和异常处理部分(以exception开头)
--语法格式:
declare
--声明部分,可选
begin
--执行部分,可选
exception
--异常处理部分,可选
end
--标识符
--分界符
% --属性指示符
:= --赋值操作符
=> --链接操作符
.. --范围操作符
|| --范围操作符
<space>空格
--数据类型
数值类型:
number(p,s) --p表示精度,s是刻度范围
pls_integer、binary_integer
字符类型: varchar2(maxlength)、char(maxlength)、long
日期类型:date
布尔类型:boolean
特殊类型:%type、record、%rowtype
%type:声明一个与指定列相同的数据类型
record:记录类型
--语法
type record_type is record --声明record类型record_type
(
var_member1 data_type [not null][:=default_value],
...
var_membern data_type [not null] [:=dafault_value]
)
record_name record_type --定义变量
%rowtype : 根据结构表中行的结构定义的特殊的数据类型,用来存储从数据表中检索到的一行数据
--语法
rowVar_name table_name%rowtype; --rowVar_name:表示存储一行数据的变量名,table_name 指定表名
-- 变量、常量的定义
语法:
<变量名><数据类型>[(长度):=<初始值>];--变量
<常量名> constant <数据类型>:=<常量值>];--变量 ,关键字:constant
-- 流程控制语句
1.if...then
2.if...then...else
3.if...then...else if...
4.case
--循环语句
5.loop...exit...end
6.loop...exit when...end
7.while...loop...end
8.for
9.goto
--if...then
declare
age int:=55;
begin
if age>54
then dbms_output.put_line("退休");
else
dbms_output.put_line("不能退休");
end if;
end;
--case
declare
season int:=3;
aboutinfo varchar2(50);
begin
case season
when 1 then
aboutinfo:=season||'季度包括1,2,3月份';
when 2 then
aboutinfo:=season||'季度包括1,2,3月份';
else
aboutinfo:=season||'不合法';
end case;
end;
--loop...exit
declare
sum int:=0;
i int:=0;
begin
loop
i:=i+1;
sum:=sum+i;
exit when i=10;
end loop;
end;
--while...loop...end
declare
s int:=1;
i int:=0;
begin
while i>10 loop
i:=i+1;
s:=s*i;
end loop;
end;
-- for
declare
sum int:=0;
begin
for i in reverse 1...100 loop
if mod(i,2)=0 then
sum:=sum+i;
end if;
end loop;
end;
---游标
声明游标
--语法
cursor cur_name(input_parameter1,...)
[return ret_type]--可选,返回值类型
is select_sentence --select语句,反复读取结果集
--例子:
declare
cursor cur_emp(var_job in varchar2:='11')
is select empno,ename,sal
from emp
where job=var_job;
--打开游标
open curso_name; --有参数的要带参数,默认可以不用带参数;
--读取游标
fetch ...into ...
--fetch 游标名称 into 记录变量
--关闭游标
close cursor_name;
--隐式游标(处理数据操纵语句,如update,delete语句)
--游标的属性
%found:布尔类型,如果sql语句影响到一行数据,为trun,否则为false;
%notfound :与%found相反;
%rowcount:游标行数
%ISOPEN:游标是否打开;
1.写一段PL/SQL语句,使用loop语句求得前10各自然数的积
declare
int i:=0;
int s:=1;
begin
loop
i:=i+1;
s:=s*i;
exit when i=10;
end loop;
dbms_output.put_line(s):
end;