plsql
片段:编写的一段plsql代码段
-
列类型
declare eid number; mydate emp.hiredate%type; --表.列%type:获取该列的类型 begin eid:=&请输入; --:=plsql的赋值 &手动输入 end;
-
行类型
declare myrow emp%rowtype; --表%rowtype:行类型 sid number; begin sid:=7396; select * into myrow from emp where empno=sid; --获取出来的行类型用.列的方式取值 dbms_output.put_line(myrow.ename||myrow.empno||...); --dbms_output.put_line();数据库输出一行 end;
-
循环
<<***>>循环
declare i number; begin i:=1; <<one_loop>> --循环标记 loop --开始 i:=i+1; dbms_output.put_line(i); exit one_loop when i=100; --退出条件 end loop; --结束 end;
while循环
declare i number;
mysum number;
begin
i:=1;
mysum:=0;
while i<=100 loop
mysum:=mysum+i;
i:=i+i;
end loop;
dbms_output.put_line(mysum);
end;
for循环
declare mysum number; --for循环不需要初始化i
begin
mysum:=0;
for i in 1..100 loop
mysum:mysum+i;
end loop;
dbms_output.put_line(mysum);
end;
- 条件结构
-----if
declare eid number;
begin
eid:=7963;
select sal into mysal from emp where empno=eid;
if mysql>3500 then
---------------
elsif mysal=2000 then
----------------
else
----------------
end if;
end;
-----case
declare eid number;
begin
eid:=7963;
select sal into mysal from emp where empno=eid;
case mysql when 3500 then
---------------
case mysal when 2000 then
----------------
end case;
end;
- 异常处理
declare eename varchar;
begin
select * into eename from emp;
exception when too_many_rows then dbms_output.put_line('行数太多'); --异常处理
end;
自定义异常并抛出异常
declare ex exception;
begin
raise ex; --抛出自定义异常ex
exception when ex then
dbms_output.put_line('我是自定义异常');
end;
函数
create or replace function f_test1(eid number)return varchar2
is --定义需要的变量 ps:函数必须有参数,返回值不需要长度.
str varchar2(20);
begin
str:='函数返回值';
return str;
end;
--函数定义后可以到左边的Functions里去看看是否正确。
代码段调用函数
declare str varchar;
begin
str:=f_test1(1);
dbms_output.put_line(str);
end;