ORACLE PL/SQL Programming 17-过程、函数、参数

12c中的with与函数的结合

在sql语句中用到函数是会发生sql和pl/sql引擎的上下问切换,在12C版本中可以用with来避免这个切换,来提升性能

如下

WITH FUNCTION full_name (fname_in IN VARCHAR2, lname_in IN VARCHAR2)
        RETURN VARCHAR2
     IS
     BEGIN
        RETURN fname_in || ' ' || lname_in;
     END;

SELECT full_name(first_name, last_name)
  FROM employees

利用表函数和游标的结合来将复杂的数据结构传递给JDBC

例如把一个嵌套表转换为游标形式就可以如下操作,

CREATE TYPE pet_t IS OBJECT (
   NAME    VARCHAR2 (60)
 , breed   VARCHAR2 (100)
 , dob     DATE
);
/

CREATE TYPE pet_nt IS TABLE OF pet_t;
/

CREATE OR REPLACE FUNCTION pet_family (dad_in IN pet_t, mom_in IN pet_t)
   RETURN pet_nt
IS
   l_count   PLS_INTEGER;
   retval    pet_nt      := pet_nt ();
BEGIN
   retval.EXTEND;
   retval (retval.LAST) := dad_in;
   retval.EXTEND;
   retval (retval.LAST) := mom_in;

   IF mom_in.breed = 'RABBIT'
   THEN
      l_count := 12;
   ELSIF mom_in.breed = 'DOG'
   THEN
      l_count := 4;
   ELSIF mom_in.breed = 'KANGAROO'
   THEN
      l_count := 1;
   END IF;

   FOR indx IN 1 .. l_count
   LOOP
      retval.EXTEND;
      retval (retval.LAST) :=
                         pet_t ('BABY' || indx, mom_in.breed, SYSDATE - indx);
   END LOOP;

   RETURN retval;
END pet_family;
/

REM Call the table function within a SELECT staement.

SELECT pets.NAME, pets.dob
  FROM TABLE (pet_family (pet_t ('Hoppy', 'RABBIT', SYSDATE)
                        , pet_t ('Hippy', 'RABBIT', SYSDATE)
                         )
             ) pets;

REM Place the same query inside a PL/SQL function returning a cursor variable.
 
CREATE OR REPLACE FUNCTION pet_family_cv
   RETURN sys_refcursor
IS
   retval   sys_refcursor;
BEGIN
   OPEN retval FOR
      SELECT *
        FROM TABLE (pet_family (pet_t ('Hoppy', 'RABBIT', SYSDATE)
                              , pet_t ('Hippy', 'RABBIT', SYSDATE)
                               )
                   );

   RETURN retval;
END pet_family_cv;
/

数据流函数

在做ETL转换的时候,把一行数据转换成两行,或者把两行数据转换成一行。
下面的一个原始股票信息stocktable中的一行数据拆分到另一个表中tickertable,
建表信息如下:

--这个表含股票代码,交易日期,开盘价,收盘价,这几个要素都在一行中
CREATE TABLE  stocktable (
  ticker VARCHAR2(20),
  trade_date DATE,
  open_price NUMBER,
  close_price NUMBER
)
/

--这个表是开盘价格和收盘价格各占一行
CREATE TABLE tickertable
(
  ticker VARCHAR2(20),
  pricedate DATE,
  pricetype VARCHAR2(1),
  price NUMBER
)
/

传统方式:

  1. pl/sql
FOR rec IN  (SELECT *
                  FROM stocktable)
   LOOP
      INSERT INTO tickertable
                  (ticker, pricetype, price)
           VALUES (rec.ticker, 'O', rec.open_price);

      INSERT INTO tickertable
                  (ticker, pricetype, price)
           VALUES (rec.ticker, 'C', rec.close_price);
   END LOOP;
  1. 纯sql解决方案
insert ALL 
INTO tickertable
  (ticker,
   pricetype,
   price)
VALUES
  (ticker,
   'O',
   open_price) 
INTO tickertable
  (ticker,
   pricetype,
   price)
VALUES
  (ticker,
   'C',
   close_price)
  select ticker,
         trade_date,
         open_price,
         close_price
    FROM stocktable;
    

数据流函数解决方案

大致思路:

  1. 在schema中创建基于表stocktable的object对象,然后创建基于对象的嵌套表
CREATE TYPE tickertype AS OBJECT (
   ticker      VARCHAR2 (20)
 , pricedate   DATE
 , pricetype   VARCHAR2 (1)
 , price       NUMBER
);
/

CREATE TYPE tickertypeset AS TABLE OF tickertype;
/
  1. 创建基于表stocktable的ref cursor(游标类型)
CREATE OR REPLACE PACKAGE refcur_pkg
IS
   TYPE refcur_t IS REF CURSOR
      RETURN stocktable%ROWTYPE;
END refcur_pkg;
/sql

  1. 编写透视函数
CREATE OR REPLACE FUNCTION stockpivot (dataset refcur_pkg.refcur_t)
   RETURN tickertypeset
IS
   out_obj     tickertype    := tickertype (NULL, NULL, NULL, NULL);
   
   TYPE dataset_tt IS TABLE OF stocktable%ROWTYPE
      INDEX BY PLS_INTEGER;
   l_dataset   dataset_tt;
   
   /* The nested table that will be returned. */
   retval      tickertypeset := tickertypeset ();
BEGIN
   LOOP
      /* Move N rows from cursor variable (SELECT) to local collection. */
      FETCH dataset
      BULK COLLECT INTO l_dataset LIMIT 100;

      EXIT WHEN l_dataset.COUNT = 0;
      
      /* Iterate through each row.... */
      FOR l_row IN 1 .. l_dataset.COUNT
      LOOP
         /* START application specific logic.
            This will vary depending on your transformation. */
            
         /* Create open price object type and add to collection. */
         out_obj.ticker := l_dataset (l_row).ticker;
         out_obj.pricetype := 'O';
         out_obj.price := l_dataset (l_row).open_price;
         out_obj.pricedate := l_dataset (l_row).trade_date;
         retval.EXTEND;
         retval (retval.LAST) := out_obj;
         
         /* Create close price object type and add to collection. */
         out_obj.pricetype := 'C';
         out_obj.price := l_dataset (l_row).close_price;
         out_obj.pricedate := l_dataset (l_row).trade_date;
         retval.EXTEND;
         retval (retval.LAST) := out_obj;
      END LOOP;
   END LOOP;

   CLOSE dataset;

   RETURN retval;
END;
/
  1. 编写插入sql语句

这个地方用到了游标表达式和table函数

BEGIN
   INSERT INTO tickertable
      SELECT *
        FROM TABLE (stockpivot (CURSOR (SELECT *
                                          FROM stocktable)));
END;
/

管道函数

管道函数可以用在分页当中,当用户需要分页的时候才正整执行查询,而不是进入第一页就执行全部查询,这样能提升性能,如下:

CREATE OR REPLACE FUNCTION stockpivot_pl (dataset refcur_pkg.refcur_t)
   RETURN tickertypeset PIPELINED --此处加入管道声明
IS
   l_row_as_object   tickertype  := tickertype (NULL, NULL, NULL, NULL);

   TYPE dataset_tt IS TABLE OF dataset%ROWTYPE
      INDEX BY PLS_INTEGER;

   l_dataset         dataset_tt;
   l_row             PLS_INTEGER;
BEGIN
   FETCH dataset
   BULK COLLECT INTO l_dataset;
   CLOSE dataset;

   l_row := l_dataset.FIRST;

   WHILE (l_row IS NOT NULL)
   LOOP
      -- first row
      l_row_as_object.ticker := l_dataset (l_row).ticker;
      l_row_as_object.pricetype := 'O';
      l_row_as_object.price := l_dataset (l_row).open_price;
      l_row_as_object.pricedate := l_dataset (l_row).trade_date;
      --PIPE ROW 是关键
      PIPE ROW (l_row_as_object);
      -- second row
      l_row_as_object.pricetype := 'C';
      l_row_as_object.price := l_dataset (l_row).close_price;
      --
      PIPE ROW (l_row_as_object);
      l_row := l_dataset.NEXT (l_row);
   END LOOP;

   RETURN; --注意,return没有返回任何东西,执行单纯的return即程序结束,返回上一级
END;
/

使用的时候这样使用:

BEGIN
    
      INSERT INTO tickertable
         SELECT *
           FROM TABLE (stockpivot_pl (CURSOR (SELECT *
                                                FROM stocktable)))
          WHERE ROWNUM < 10;
END;

确定性函数

确定性函数就是无论任何时候,传入的参数是123,返回的总是456,跟数据库的具体数据变化无关,对于一些自定义的字符串处理函数我们可以声明下是确定函数,在return函数后面加上 DETERMINISTIC 即可。


CREATE OR REPLACE FUNCTION betwnstr (
   string_in   IN   VARCHAR2
 , start_in    IN   INTEGER
 , end_in      IN   INTEGER
)
   RETURN VARCHAR2 DETERMINISTIC
IS
BEGIN
   DBMS_LOCK.sleep (.01);
   RETURN (SUBSTR (string_in, start_in, end_in - start_in + 1));
END;
/

你可能感兴趣的:(PL/SQL)