Oracle帶輸入輸出引數的儲存過程

zhenghaishu發表於2014-08-10
Oracle帶輸入輸出引數的儲存過程

(一)使用輸入引數
需求:在emp_copy中新增一條記錄,empno為已有empno的最大值+1,ename不能為空且長度必須大於0,deptno為60。
建立儲存過程:
create or replace procedure insert_emp(emp_name in varchar2, dept_no in number) as
begin
  declare max_empno number;
  begin
    if(emp_name is null or length(emp_name) = 0) then
      return;
    end if;

    if(dept_no != 60) then
      return;
    end if;

    select max(empno) into max_empno from emp_copy;
    insert into emp_copy(empno, ename, deptno) values(max_empno + 1, emp_name, dept_no);
  end;
end insert_emp;
/

Procedure created.

呼叫儲存過程並驗證:
(1)
SQL>execute insert_emp('Li Si', 60);
PL/SQL procedure successfully completed.

SQL>
col empno format 99999;
col ename format a15;
col deptno format 99999;
select empno, ename, deptno from emp_copy where deptno = 60;

 EMPNO ENAME           DEPTNO
------ --------------- ------
  7981 Li Si           60

(2)
SQL> execute insert_emp('', 6);
PL/SQL procedure successfully completed.

SQL> select empno, ename, deptno from emp_copy where deptno = 6;

SQL>

(二)使用輸出引數
需求:在上個需求的基礎上,要分別統計表emp_copy插入資料前後的記錄數。
建立儲存過程:
create or replace procedure insert_emp(emp_name in varchar2, dept_no in number, original_count out number, current_count out number) as
begin
  declare max_empno number;
  begin
    if(emp_name is null or length(emp_name) = 0) then
      return;
    end if;

    if(dept_no != 60) then
      return;
    end if;

    select count(1) into original_count from emp_copy;
    select max(empno) into max_empno from emp_copy;
    insert into emp_copy(empno, ename, deptno) values(max_empno + 1, emp_name, dept_no);
    select count(1) into current_count from emp_copy;
  end;
end insert_emp;
/

Procedure created.

呼叫儲存過程:
declare count1 number;
        count2 number;
begin
  insert_emp('Wang Wu', 60, count1, count2);
  dbms_output.put_line('Original count of table emp_copy is ' || count1);
  dbms_output.put_line('Current count of table emp_copy is ' || count2);
end;
/

Original count of table emp_copy is 15
Current count of table emp_copy is 16

PL/SQL procedure successfully completed.


(三)使用輸入輸出引數
in out引數綜合了上述兩種引數型別,既向過程體傳值,也被賦值而傳到過程體外。in out引數既可以用作輸入也可以用作輸出。
需求:實現兩數交換。
建立儲存過程:
create or replace procedure swap(value1 in out number, value2 in out number) as
begin
  value1 := value1 + value2;
  value2 := value1 - value2;
  value1 := value1 - value2;
end swap;
/

Procedure created.

呼叫儲存過程:
declare a number := 22;
        b number := 33;
begin
  dbms_output.put_line('Before swap: a = ' || a || ', b = ' || b);
  swap(a, b);
  dbms_output.put_line('After swap: a = ' || a || ', b = ' || b);
end;
/

Before swap: a = 22, b = 33
After swap: a = 33, b = 22

PL/SQL procedure successfully completed.






來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29485627/viewspace-1248721/,如需轉載,請註明出處,否則將追究法律責任。

相關文章