---------------------目录------------------
一、数据类型
二、一些常用语法
三、控制语句及例子
四、游标
五、函数和存储过程
六、包的创建和调用
-------------------------------------------
基础知识:
DDL语句:数据定义语言 如:createdropalter;
DML语句:数据操作语言 如:update insert delete;
DCL语句:数据库控制语言 如:grant;
DCL语句:数据库查询语言 如:select;
一、数据类型
整数 v_num number(5);
浮点数 v_floatnum number(6, 2);
字符串变长 v_name varchar2(20):='TEST';
字符串固定长 v_hello char(10);
布尔值 v_flag boolean;
二、一些常用的语法
%type 提取字段的类型
%rowtype 提取表所有字段的类型
%type 关键字,相当于定义一个结构体
三、控制语句及例子
1、语句块
1)declare (变量声明、初始化) begin(业务逻辑处理代码)end;
例子:
declare
rowcount number(5);
begin
select count(*) into rowcount from testtable;
commit;
end;
2)declare (变量声明、初始化) begin(业务逻辑处理代码)exception(异常捕获)end;
2、判断语句
1)if ..(条件表达式)....then ....(业务逻辑处理)....end if;
如:
declare
rowcount number(5);
begin
select count(*) into rowcount from testtable;
if rowcount = 0 then
dbms_output.put_line('error');
end if;
commit;
end;
2)多分支
if <条件表达式> then
...(业务逻辑处理)...
else if <条件表达式> then
...(业务逻辑处理).....
else
...(业务逻辑处理).....
end if;
end if;
例子:
declare
rowcount number(5);
begin
select count(*) into rowcount from testtable;
if rowcount = 0 then
dbms_output.put_line('count == 0');
else if rowcount = 1 then
dbms_output.put_line('count == 1');
else rowcount > 1 then
dbms_output.put_line('count > 1');
end if;
end if;
commit;
end;
注意:有多少个if就有多少个end if;
3、循环语句
1)loop循环语法:
loop ..(逻辑处理)....; exit when <表达式>; end loop;
例子:
declare
num NUMBER(2) := 0;
begin loop
num := num + 1;
dbms_output.put_line('loop end');
exit when num = 10;
end loop;
end;
2)while循环语法:
while <表达式> loop ...(逻辑处理)...; end loop;
例子:
declare
num NUMBER(2) := 0;
begin
while num < 10 loop
dbms_output.put_line('loop .....');
num := num + 1;
end loop;
end;
3)for循环语句
for <变量> in <变量取值范围(小值..大值,如1..100)> loop end loop;
例子:
declare
num NUMBER(2) := 0;
begin
for num in 1..9 loop
dbms_output.put_line('loop .....');
num := num + 1;
end loop;
end;
3)case语句
case ...
when ...
then...;
when ...
then ...;
end case;
四、游标
1、作用
定位结果集的一个元素对象的位置,从而可以获得该元素对象的信息。
2、游标的属性:
%isopen 判断游标是否打开;
%notfound 当前的FETCH操作没有返回数据行时,为true,否则为false;
%found 与上述相反;
%rowcount 返回游标的记录数量;
3、游标的使用:step1 声明游标
step2 打开游标
step3 获取游标制定的数据
step4 关闭游标
例子一:
declare
cursor res is select * from testtable;
begin
open res;
loop
fetch res into iterm;
exit whenres%notfound;
dbms_output.put_line(iterm.name);
end loop;
close res;
end;
例子二:游标和for一起使用,隐式游标(不需要open fetch 和close)
declare
cursor res is select * from testtable;
begin
for iterm in res loop
dbms_output.put_line(iterm.name);
end loop;
end;