Oracle简单学习

时间:2021-07-05 16:56:38

最近一段时间重温了oracle关于存储过程和oracle包以及function中的定义, 先看一下要用的表:

devices(id number, name varchar2, age number)

Oracle简单学习

groups(id number, devicesid number, name varchar2, content varchar2)

Oracle简单学习

在oracle中建立如下的package和package bodies,

Oracle简单学习

下面给出里面具体的内容:

首先是packges下面的devices_pkg内容:

定义三个function和一个procedure

CREATE OR REPLACE PACKAGE DEVICES_PKG
IS  
  
  TYPE MY_RESULTSET_CURSOR IS REF CURSOR;
  
  FUNCTION fun_add_device(
                     dev_id   NUMBER, 
                     dev_name VARCHAR2, 
                     dev_age  NUMBER)
  RETURN NUMBER;
 
  FUNCTION fun_delete_device(dev_id NUMBER)
  RETURN NUMBER;
  
  FUNCTION fun_Get_Test_Main_All
  RETURN MY_RESULTSET_CURSOR;
  
  PROCEDURE pro_select_device(dev_id NUMBER, RS out MY_RESULTSET_CURSOR);
  
END DEVICES_PKG;

然后是packages bodies里面的内容:

这里面主要是对上面定义的function和procedure的实现定义,

有简单的返回, 还有游标类型的返回;

CREATE OR REPLACE PACKAGE BODY DEVICES_PKG
AS

FUNCTION fun_add_device(dev_id NUMBER, 
                     dev_name VARCHAR2, 
                     dev_age NUMBER)
RETURN NUMBER
IS
BEGIN
    INSERT INTO devices VALUES (dev_id, dev_name, dev_age);
    IF SQL%FOUND THEN
       RETURN 1;
    ELSE
       RETURN 0;
    END IF;
END fun_add_device;


FUNCTION fun_delete_device(dev_id NUMBER)
RETURN NUMBER
IS 
BEGIN   
    DELETE FROM devices WHERE id = dev_id;
    IF SQL%FOUND THEN
       RETURN 1;
    ELSE
       RETURN 0;
    END IF;
END fun_delete_device;

FUNCTION fun_Get_Test_Main_All
RETURN MY_RESULTSET_CURSOR
IS
return_cursor MY_RESULTSET_CURSOR;
BEGIN
  OPEN return_cursor FOR SELECT d.id,d.name,d.age FROM devices d ORDER BY d.id ASC;
  RETURN return_cursor;
END;

PROCEDURE pro_select_device(dev_id NUMBER, RS out MY_RESULTSET_CURSOR)
IS
testCursor MY_RESULTSET_CURSOR;
testRec devices%ROWTYPE;
v_sql_select VARCHAR2(500);
BEGIN
  v_sql_select := select   
                  d.name, d.age, g.content
                  from devices d, groups g
                  where d.id =|| dev_id ||
                   and d.id = g.devicesid;
  OPEN RS FOR v_sql_select;
  testCursor := fun_Get_Test_Main_All();
  LOOP
    FETCH testCursor INTO testRec;     
    EXIT WHEN testCursor%NOTFOUND;
    DBMS_OUTPUT.put_line(id:||testRec.Id||,name:||testRec.Name||,age:||testRec.Age);
  END LOOP;
END;

END DEVICES_PKG;

这里给出其中一个调用的过程:

Oracle简单学习

测试devices_pkg.pro_select_device这个存储过程,

输入dev_id为3,

结果rs为:

Oracle简单学习

然后看一下DBMS输出是什么:

Oracle简单学习