您好,欢迎访问一九零五行业门户网

Oracle存储过程语法

下面写一个简单的例子来对以上所说的存储过程的用法做一个应用: 现假设存在两张表,一张是学生成绩表(studnet) ,字段为:stdid
1  create or replace procedure 存储过程名
2  is
3  begin
4  null;
5  end;
行1:
create or replace procedure 是一个sql语句通知oracle数据库去创建一个叫做skeleton存储过程, 如果存在就覆盖它;
行2:
is关键词表明后面将跟随一个pl/sql体。
行3:
begin关键词表明pl/sql体的开始。
行4:
null pl/sql语句表明什么事都不做,这句不能删去,,因为pl/sql体中至少需要有一句;
行5:
end关键词表明pl/sql体的结束
存储过程创建语法:
 create or replace procedure 存储过程名(param1 in type,param2 out type)
as
变量1 类型(值范围); --vs_msg   varchar2(4000);
变量2 类型(值范围);
begin
select count(*) into 变量1 from 表a where列名=param1;
    if (判断条件) then
       select 列名 into 变量2 from 表a where列名=param1;
       dbms_output。put_line(‘打印信息’);
    elsif (判断条件) then
       dbms_output。put_line(‘打印信息’);
    else
       raise 异常名(no_data_found);
    end if;
exception
    when others then
       rollback;
end;
注意事项:
1, 存储过程参数不带取值范围,in表示传入,out表示输出
类型可以使用任意oracle中的合法类型。
2,  变量带取值范围,后面接分号
3,  在判断语句前最好先用count(*)函数判断是否存在该条操作记录
4,  用select 。。。into。。。给变量赋值
5,  在代码中抛异常用 raise+异常名
create or replace procedure存储过程名
(
--定义参数
 is_ym  in char(6) ,
the_count out number,
)
as
--定义变量
vs_msg   varchar2(4000);   --错误信息变量
vs_ym_beg  char(6);      --起始月份
vs_ym_end  char(6);      --终止月份
vs_ym_sn_beg char(6);     --同期起始月份
vs_ym_sn_end char(6);     --同期终止月份
--定义游标(简单的说就是一个可以遍历的结果集)
cursor cur_1 is
  select 。。。
  from 。。。
    where 。。。
   group by 。。。;
begin
--用输入参数给变量赋初值,用到了oralce的
substr
to_char
add_months
to_date 等很常用的函数。
vs_ym_beg := substr(is_ym,1,6);
vs_ym_end := substr(is_ym,7,6);
vs_ym_sn_beg := to_char(add_months(to_date(vs_ym_beg,'yyyymm'), -12),'yyyymm');
vs_ym_sn_end := to_char(add_months(to_date(vs_ym_end,'yyyymm'), -12),'yyyymm');
--先删除表中特定条件的数据。
delete from 表名 where ym = is_ym;
  --然后用内置的dbms_output对象的put_line方法打印出影响的记录行数,其中用到一个系统变量sql%rowcount
dbms_output.put_line('del上月记录='||sql%rowcount||'条');
insert into表名(area_code,ym,cmcode,rmb_amt,usd_amt)
select area_code,is_ym,cmcode,sum(rmb_amt)/10000,sum(usd_amt)/10000
from bgd_area_cm_m_base_t
  where ym >= vs_ym_beg
  and ym <= vs_ym_end
group by area_code,cmcode;
dbms_output.put_line('ins当月记录='||sql%rowcount||'条');
--遍历游标处理后更新到表。遍历游标有几种方法,用for语句是其中比较直观的一种。
for rec in cur_1 loop
  update 表名
  set rmb_amt_sn = rec.rmb_amt_sn,usd_amt_sn = rec.usd_amt_sn
   where area_code = rec.area_code
   and cmcode = rec.cmcode
   and ym = is_ym;
end loop;
commit;
--错误处理部分。others表示除了声明外的任意错误。sqlerrm是系统内置变量保存了当前错误的详细信息。
exception
   when others then
      vs_msg := 'error in xxxxxxxxxxx_p('||is_ym||'):'||substr(sqlerrm,1,500);
rollback;
   --把当前错误记录进日志表。
   insert into log_info(proc_name,error_info,op_date)
   values('xxxxxxxxxxx_p',vs_msg,sysdate);
   commit;
   return;
end;
其它类似信息

推荐信息