Table functions - Planboard Symposium 2013
Upcoming SlideShare
Loading in...5
×
 

Table functions - Planboard Symposium 2013

on

  • 728 views

Er is een stelling: 'If you can do it in SQL, use SQL.' Maar soms is zelfs de zeer krachtige Oracle versie van SQL niet genoeg en heb je behoefte aan méér, zoals loops, condities etc. ...

Er is een stelling: 'If you can do it in SQL, use SQL.' Maar soms is zelfs de zeer krachtige Oracle versie van SQL niet genoeg en heb je behoefte aan méér, zoals loops, condities etc.
Oracle biedt sinds Oracle 9i de mogelijkheid om PL/SQL-code te bouwen en op te nemen in de FROM clause van je query. Hoe? Door de output van een PL/SQL functie zo te formatteren dat die op een tabel lijkt, dus met records van waarden (rijen met kolommen). Hiermee heb je alle kracht van PL/SQL én SQL tot je beschikking in je SQL-statement.
Deze aanpak biedt nóg een voordeel: de code in de PL/SQL-functie wordt slechts éénmaal uitgevoerd, en niet voor elke rij (functie in de WHERE-clause) of voor elke rij in het resultaat (functie in de SELECT).

If you can do it in SQL, use SQL

Statistics

Views

Total Views
728
Views on SlideShare
728
Embed Views
0

Actions

Likes
0
Downloads
9
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Table functions - Planboard Symposium 2013 Table functions - Planboard Symposium 2013 Presentation Transcript

  • Patrick.Barel@AMIS.nltechnology.amis.nlblog.bar-solutions.com
  • About me…• Patrick Barel• Working with Oracle since 1997• Working with PL/SQL since 1999• Playing with APEX since 2003 (mod_plsql)• ACE since 2011• OCA since December 20th 2012
  • Read me…http://blog.bar-solutions.comhttp://technology.amis.nlhttp://allthingsoracle.com
  • Download me…Plugins for PL/SQL Developerhttp://bar-solutions.comPlugins for Apexhttp://apex-plugin.com
  • Watch me…
  • Patrick.Barel@GMail.comContact me…@patch72 patrick@bar-solutions.comPatrick.Barel@AMIS.nlPatrick.Barel@GMail.com302915640338721Patrick Barel
  • Patrick Barel, AMIS Mai 28th 2013Table FunctionsPL/SQL in SQL
  • Overview ofTable FunctionsTable Function ConceptsUsing Table FunctionsTable functions
  • Table functions are functions that produce acollection of rows (either a nested table or avarray) that can be queried like a physicaldatabase table.You use a table function like thename of a database table, in the FROM clause ofa query.Overview of table functions
  • Define Record TypeDefine NestedTable typeDefine function returning NestedTable typeQuery function using the TABLE() operatorTable function concepts
  • • Defined as an object table of a collection– First an object typeSQL> CREATE TYPE now_t AS OBJECT2 (now VARCHAR2(8));3 /Type created.Table function concepts, result set
  • • Defined as an object table of a collection– Second; the collection typeSQL> CREATE TYPE now_tt AS2 TABLE OF now_t;3 /Type created.Table function concepts, result set
  • • Return type is the object tableCREATE OR REPLACE FUNCTION nowRETURN now_tt ASl_returnvalue now_tt := now_tt();…BEGIN…RETURN l_returnvalue;END;Table function concepts, function
  • • Queried with the TABLE functionSELECT *FROM TABLE(now);Table function concepts, function
  • CREATE OR REPLACE FUNCTION now RETURN now_tt ASl_returnvalue now_tt := now_tt();l_now VARCHAR2(8);BEGINFOR counter IN 1 .. 4 LOOPl_now := to_char(SYSDATE, HH24:MI:SS);dbms_lock.sleep(1);l_returnvalue.extend;l_returnvalue(l_returnvalue.last) := now_t(l_now);END LOOP;RETURN l_returnvalue;END;Table function concepts, simple function
  • SQL> SELECT *2 FROM TABLE(now)3 /NOW--------16:54:2116:54:2216:54:2316:54:244 rows selected.Table function concepts, simple function
  • • Query results passed as a parameter– Parameter type is REF CURSOR– SYS_REFCURSOR can be usedfor weakly typed optionCREATE OR REPLACE FUNCTION now_and_then(cursor_in SYS_REFCURSOR )RETURN now_and_then_tt ASTable function concepts, nesting functions
  • • CURSOR keyword denotes value passedwithin querySELECT *FROM TABLE(now_and_then( CURSOR ( SELECT *FROM TABLE(now))))/Table function concepts, nesting functions
  • CREATE OR REPLACE FUNCTION now_and_then(cursor_in SYS_REFCURSOR)RETURN now_and_then_tt ASl_returnvalue now_and_then_tt := now_and_then_tt();l_now VARCHAR2(8);l_then VARCHAR2(8);BEGINLOOPFETCH cursor_inINTO l_now;EXIT WHEN cursor_in%NOTFOUND;l_then := to_char(SYSDATE, HH24:MI:SS);l_returnvalue.extend;l_returnvalue(l_returnvalue.last) :=now_and_then_t(l_now, l_then);END LOOP;RETURN l_returnvalue;END;Table function concepts, nested function
  • SQL> SELECT *2 FROM TABLE ( now_and_then( CURSOR( SELECT *3 FROM TABLE ( now ))))4 /NOW AND_THEN-------- --------16:58:51 16:58:5516:58:52 16:58:5516:58:53 16:58:5516:58:54 16:58:554 rows selected.Table function concepts, nested function
  • • Function can be pipelined• Produce results as they are created– Returning results one record at a timePipelined table functions
  • • Adding PIPELINED keyword to functionspecification• Actual return datatype is collection• PIPE ROW function returns single record tocalling process and then continues processing• Return is still requiredCREATE OR REPLACE FUNCTION nowRETURN now_tPIPELINED ASl_returnvalue single_time_t;BEGINloop...PIPE ROW(l_returnvalue);...end loop;RETURN;END;Pipelining : syntax
  • CREATE OR REPLACE FUNCTION nowRETURN now_ttPIPELINED ASl_returnvalue now_t;l_now VARCHAR2(8);BEGINFOR counter IN 1 .. 4 LOOPdbms_lock.sleep(2);l_now := to_char(SYSDATE, HH24:MI:SS);l_returnvalue := now_t(l_now);PIPE ROW (l_returnvalue);END LOOP;RETURN;END;Pipelined function
  • SQL> SELECT *2 FROM TABLE(now_and_then(CURSOR(SELECT *3 FROM TABLE(now))))4 /NOW AND_THEN-------- --------19:54:15 19:54:1519:54:17 19:54:1719:54:19 19:54:193 rows selected.Pipelined functionWithout pipeliningit would be:NOW AND_THEN-------- --------19:54:15 19:54:1919:54:17 19:54:1919:54:19 19:54:19now_and_then.sql
  • • Functions can be parallelized• If the source data can be processed inparallel, the functions can be processedin parallelParallel table functions
  • Typical data processingStage 1OLTPF1 F2 DataWarehouseStage 2 F3Data goes through several transformations,in table functions,and then gets loaded into a database
  • Parallel & pipelined data processingOLTPF1 DataWarehouseF1F1F2F2F2F3F3F3Data goes through several transformations,in table functions, in parallel (multipleprocesses)and then gets loaded into a database
  • • Prior to Oracle9i, calling a functioninside a SQL statement causedserialization.– The parallel query mechanism could notbe used.• Now you can enable parallel executionof a table function.– This greatly increases the usability ofPL/SQL-enriched SQL in data warehouseapplications.Parallel execution and table functionsparallel.sql
  • • The table functions parameter list must consistonly of a single strongly-typed REF CURSOR.• Include the PARALLEL_ENABLE hint in theprogram header.– Choose a partition option that specifies how thefunctions execution should be partitioned.– "ANY" means that the results are independent of theorder in which the function receives the input rows(through the REF CURSOR).Enabling parallel execution{[ORDER | CLUSTERORDER | CLUSTERORDER | CLUSTERORDER | CLUSTER] BY column_list}PARALLEL_ENABLEPARALLEL_ENABLEPARALLEL_ENABLEPARALLEL_ENABLE ({PARTITIONPARTITIONPARTITIONPARTITION p BYBYBYBY[ANY | (HASH | RANGE) column_list]} )
  • PARALLEL_ENABLE (Partition p_input_rows BY ANY )CREATE OR REPLACE FUNCTION Aggregate_Xform (p_input_rows in My_Types.cur_t) RETURNMy_Types.dept_sals_tabPIPELINEDCLUSTER P_INPUT_ROWS BY (dept)PARALLEL_ENABLE( PARTITION p_input_rowsBY HASH (dept) )ORDER p_input_rows BY (c1, c2)PARALLEL_ENABLE( PARTITION p_input_rowsBY RANGE (c1) )withwithwithSimplest form, results dontvary from order in whichfunction gets input rows.All rows for a given departmentmust go to the same slave,and rows are deliveredconsecutively.Rows are delivered to aparticular slave as directed bypartition... and will be locallysorted by that slave.Examples of parallelized functions
  • Serial executionScramblealter table emp noparallel;select *from table( scramble( cursor ( select empno, ename from emp)));EMP
  • Parallel executionScrambleScrambleScrambleEMPScramblealter table emp parallel 4;select *from table( scramble( cursor ( select empno, ename from emp)));
  • - Using PL/SQL in SQL- Create script based on the table dataUsing the table function
  • • Using SQLCreate script based on the table dataDEPT(table)SQLstatementinsert into DEPT( LOC, DNAME, DEPTNO)values ( NEW YORK, ACCOUNTING, 10);insert into DEPT( LOC, DNAME, DEPTNO)values ( DALLAS, RESEARCH, 20);insert into DEPT( LOC, DNAME, DEPTNO)values ( CHICAGO, SALES, 30);insert into DEPT( LOC, DNAME, DEPTNO)values ( BOSTON, OPERATIONS, 40);
  • SQLstatementSELECT insert into DEPT( LOC, DNAME, DEPTNO) values( ||LOC||, ||DNAME||, ||DEPTNO||); lineFROM DEPT;• Using SQLCreate script based on the table data
  • SELECT *FROM table(createinsertscriptfor(DEPT));SQLstatement• Using table functionsCreate script based on the table data
  • • Using table functions• Hide complexity behind PL/SQLinterface• Don’t worry about datatypesCreate script based on the table data
  • Overview of Table FunctionsTable Function ConceptsReturn collection, query like tablePipelinedParallelUsingTable FunctionsUse PL/SQL in SQLHide complexityTable functions
  • tahiti.oracle.comFor all documentation onlineOracle PL/SQL Programming (thebook)Especially chapter 17 (by StevenFeuerstein) and chapter 21 (bySteven Feuerstein with help fromAdrian Billington)References