oracle的function和procedure返回值给shell

本文演示两个关于如何在shell中调用oracle的function和procedure,并将返回值返回给shell。

1、首在package中创建function和procedure,脚本如下:

GET_BIZ_DATE: 通过pl/sql的function拿到sysdate,并返回

GET_DATE_DIFF:通过pl/sql的procedure,在对给定的一个时间的基础上加分钟,即简单时间加减,并返回运算后的时间

create or replace package mypkg as 
    function get_biz_date return varchar2;    
    procedure get_date_diff(v_date1 in varchar2, v_diff in number, v_date2 out varchar2);    
end mypkg;

create or replace package body mypkg as
  function get_biz_date return varchar2 as
    v_date varchar2(20);
  begin
    select sysdate into v_date from dual;    
    return v_date;
  end get_biz_date;

  procedure get_date_diff(v_date1 in varchar2, v_diff in number, v_date2 out varchar2) as
  begin
    v_date2 := '';
    select to_char(to_date(v_date1,'YYYY-MM-DD hh24:mi') + v_diff / (24 * 60),'yyyymmdd hh24:mi') into v_date2 from dual;
   
sys.dbms_output.put_line(v_date2);
  end get_date_diff;
end mypkg;

 

2、创建shell脚本

1)shell调用function的脚本:

[oracle@toughhou shell]$ cat function.sh 

#!/bin/bash

str=`sqlplus -s scott/scott@ORCL_SIT <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;

   select MYPKG.GET_BIZ_DATE from dual;
   exit
EOF`

echo $str

function有一个返回值,我们可以通过"select function_name() from daul"语句取到返回值,并放入shell变量中。

 

2)shell调用procedure的脚本:

[oracle@toughhou shell]$ cat procedure.sh

#!/bin/bash

out=/home/oracle/shell/out.log
v_date1='2010-12-31 23:30'
v_diff=31

sqlplus -s scott/scott@ORCL_SIT > $out <<EOF
set heading off
set feedback off;
set verify off;
set echo off;
set serveroutput on

   var v_date varchar2;
   call MYPKG.GET_DATE_DIFF('$v_date1',$v_diff,:v_date);

   exit
EOF

echo `cat $out`

我们的procedure有一个out变量,我们通过dbms_output.put_line()函数打印变量,在sqlplus连接时设置set serveroutput on,且把sqlplus信息重定向到out.log文件中。最后通过cat out.log得到out变量的值。

 

3、测试结果

[oracle@toughhou shell]$ sh function.sh 
23-NOV-13

[oracle@toughhou shell]$ sh procedure.sh 
20110101 00:01

测试结果如预期,测试成功!

 

原文地址:https://www.cnblogs.com/toughhou/p/3778788.html