创建返回db-entities的oracle过程

时间:2016-02-24 14:10:01

标签: java oracle postgresql stored-procedures intellij-idea

我目前正在开发两个Java Web应用程序。一个使用PostgreSQL数据库,另一个使用Oracle数据库。 IDE是Intellij,OS是Windows。 使用Postgres应用程序,我们有许多存储过程来返回数据库实体,例如“顾客”。现在我试图在Oracle中做同样的事情,但似乎Oracle中的程序完全不同。我甚至无法创建一个过程,Intellij在尝试时总是给我几条错误消息。 :-(也许有人可以给我一个例子,说明如何创建一个简单的过程,从一个表中返回一个db实体列表,具体取决于搜索掩码中的几个参数,例如“name”,“last_name”,“email”作为搜索参数?这太棒了!!

1 个答案:

答案 0 :(得分:2)

CREATE PROCEDURE get_Employees(
  in_first_name IN  EMPLOYEES.FIRST_NAME%TYPE,
  in_last_name  IN  EMPLOYEES.LAST_NAME%TYPE,
  in_email      IN  EMPLOYEES.EMAIL%TYPE,
  out_cursor    OUT SYS_REFCURSOR
)
AS
BEGIN
  OPEN OUT_CURSOR FOR
  SELECT *
  FROM   Employees
  WHERE  ( in_last_name IS NULL OR last_name = in_last_name )
  AND    ( in_first_name IS NULL OR first_name = in_first_name )
  AND    ( in_email IS NULL OR email = in_email );
END;
/
SHOW ERRORS;

<强>测试

CREATE TABLE Employees ( First_name, last_name, email ) AS
SELECT 'Alice',   'Abbots', 'AA@email.net' FROM DUAL UNION ALL
SELECT 'Bob',     'Bucket', 'BB@email.net' FROM DUAL UNION ALL
SELECT 'Charlie', 'Abbots', 'CA@email.net' FROM DUAL UNION ALL
SELECT 'Denis',   'Dobbs',  'DD@email.net' FROM DUAL;

跑步:

VARIABLE cur REFCURSOR;

BEGIN
  get_Employees(
    in_first_name => 'Bob',
    in_last_name  => NULL,
    in_email      => NULL,
    out_cursor    => :cur
  );
END;
/

PRINT cur;

应该输出:

anonymous block completed
CUR
---
FIRST_NAME LAST_NAME EMAIL        
---------- --------- ------------ 
Bob        Bucket    BB@email.net 

替代测试:

SET SERVEROUTPUT ON;

DECLARE
  cur SYS_REFCURSOR;
  rec EMPLOYEES%ROWTYPE;
BEGIN
  get_Employees(
    in_first_name => 'Bob',
    in_last_name  => NULL,
    in_email      => NULL,
    out_cursor    => cur
  );

  LOOP
    FETCH cur INTO rec;
    EXIT WHEN cur%NOTFOUND;

    DBMS_OUTPUT.PUT( rec.first_name );
    DBMS_OUTPUT.PUT( ' ' );
    DBMS_OUTPUT.PUT( rec.last_name );
    DBMS_OUTPUT.PUT( ' ' );
    DBMS_OUTPUT.PUT_LINE( rec.email );
  END LOOP;

  CLOSE cur;
END;
/