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 (mo...
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.com3029156403...
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...
Define Record TypeDefine NestedTable typeDefine function returning NestedTable typeQuery function using the TABLE() operat...
• Defined as an object table of a collection– First an object typeSQL> CREATE TYPE now_t AS OBJECT2 (now VARCHAR2(8));3 /T...
• Defined as an object table of a collection– Second; the collection typeSQL> CREATE TYPE now_tt AS2 TABLE OF now_t;3 /Typ...
• Return type is the object tableCREATE OR REPLACE FUNCTION nowRETURN now_tt ASl_returnvalue now_tt := now_tt();…BEGIN…RET...
• 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 .....
SQL> SELECT *2 FROM TABLE(now)3 /NOW--------16:54:2116:54:2216:54:2316:54:244 rows selected.Table function concepts, simpl...
• Query results passed as a parameter– Parameter type is REF CURSOR– SYS_REFCURSOR can be usedfor weakly typed optionCREAT...
• CURSOR keyword denotes value passedwithin querySELECT *FROM TABLE(now_and_then( CURSOR ( SELECT *FROM TABLE(now))))/Tabl...
CREATE OR REPLACE FUNCTION now_and_then(cursor_in SYS_REFCURSOR)RETURN now_and_then_tt ASl_returnvalue now_and_then_tt := ...
SQL> SELECT *2 FROM TABLE ( now_and_then( CURSOR( SELECT *3 FROM TABLE ( now ))))4 /NOW AND_THEN-------- --------16:58:51 ...
• Function can be pipelined• Produce results as they are created– Returning results one record at a timePipelined table fu...
• Adding PIPELINED keyword to functionspecification• Actual return datatype is collection• PIPE ROW function returns singl...
CREATE OR REPLACE FUNCTION nowRETURN now_ttPIPELINED ASl_returnvalue now_t;l_now VARCHAR2(8);BEGINFOR counter IN 1 .. 4 LO...
SQL> SELECT *2 FROM TABLE(now_and_then(CURSOR(SELECT *3 FROM TABLE(now))))4 /NOW AND_THEN-------- --------19:54:15 19:54:1...
• Functions can be parallelized• If the source data can be processed inparallel, the functions can be processedin parallel...
Typical data processingStage 1OLTPF1 F2 DataWarehouseStage 2 F3Data goes through several transformations,in table function...
Parallel & pipelined data processingOLTPF1 DataWarehouseF1F1F2F2F2F3F3F3Data goes through several transformations,in table...
• Prior to Oracle9i, calling a functioninside a SQL statement causedserialization.– The parallel query mechanism could not...
• The table functions parameter list must consistonly of a single strongly-typed REF CURSOR.• Include the PARALLEL_ENABLE ...
PARALLEL_ENABLE (Partition p_input_rows BY ANY )CREATE OR REPLACE FUNCTION Aggregate_Xform (p_input_rows in My_Types.cur_t...
Serial executionScramblealter table emp noparallel;select *from table( scramble( cursor ( select empno, ename from emp)));...
Parallel executionScrambleScrambleScrambleEMPScramblealter table emp parallel 4;select *from table( scramble( cursor ( sel...
- 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 Y...
SQLstatementSELECT insert into DEPT( LOC, DNAME, DEPTNO) values( ||LOC||, ||DNAME||, ||DEPTNO||); lineFROM DEPT;• Using SQ...
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 tab...
Overview of Table FunctionsTable Function ConceptsReturn collection, query like tablePipelinedParallelUsingTable Functions...
tahiti.oracle.comFor all documentation onlineOracle PL/SQL Programming (thebook)Especially chapter 17 (by StevenFeuerstein...
Table functions - Planboard Symposium 2013
Table functions - Planboard Symposium 2013
Table functions - Planboard Symposium 2013
Upcoming SlideShare
Loading in …5
×

Table functions - Planboard Symposium 2013

914 views
842 views

Published on

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

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
914
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Table functions - Planboard Symposium 2013

  1. 1. Patrick.Barel@AMIS.nltechnology.amis.nlblog.bar-solutions.com
  2. 2. 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
  3. 3. Read me…http://blog.bar-solutions.comhttp://technology.amis.nlhttp://allthingsoracle.com
  4. 4. Download me…Plugins for PL/SQL Developerhttp://bar-solutions.comPlugins for Apexhttp://apex-plugin.com
  5. 5. Watch me…
  6. 6. Patrick.Barel@GMail.comContact me…@patch72 patrick@bar-solutions.comPatrick.Barel@AMIS.nlPatrick.Barel@GMail.com302915640338721Patrick Barel
  7. 7. Patrick Barel, AMIS Mai 28th 2013Table FunctionsPL/SQL in SQL
  8. 8. Overview ofTable FunctionsTable Function ConceptsUsing Table FunctionsTable functions
  9. 9. 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
  10. 10. Define Record TypeDefine NestedTable typeDefine function returning NestedTable typeQuery function using the TABLE() operatorTable function concepts
  11. 11. • 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
  12. 12. • 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
  13. 13. • 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
  14. 14. • Queried with the TABLE functionSELECT *FROM TABLE(now);Table function concepts, function
  15. 15. 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
  16. 16. SQL> SELECT *2 FROM TABLE(now)3 /NOW--------16:54:2116:54:2216:54:2316:54:244 rows selected.Table function concepts, simple function
  17. 17. • 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
  18. 18. • CURSOR keyword denotes value passedwithin querySELECT *FROM TABLE(now_and_then( CURSOR ( SELECT *FROM TABLE(now))))/Table function concepts, nesting functions
  19. 19. 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
  20. 20. 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
  21. 21. • Function can be pipelined• Produce results as they are created– Returning results one record at a timePipelined table functions
  22. 22. • 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
  23. 23. 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
  24. 24. 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
  25. 25. • Functions can be parallelized• If the source data can be processed inparallel, the functions can be processedin parallelParallel table functions
  26. 26. Typical data processingStage 1OLTPF1 F2 DataWarehouseStage 2 F3Data goes through several transformations,in table functions,and then gets loaded into a database
  27. 27. Parallel & pipelined data processingOLTPF1 DataWarehouseF1F1F2F2F2F3F3F3Data goes through several transformations,in table functions, in parallel (multipleprocesses)and then gets loaded into a database
  28. 28. • 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
  29. 29. • 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]} )
  30. 30. 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
  31. 31. Serial executionScramblealter table emp noparallel;select *from table( scramble( cursor ( select empno, ename from emp)));EMP
  32. 32. Parallel executionScrambleScrambleScrambleEMPScramblealter table emp parallel 4;select *from table( scramble( cursor ( select empno, ename from emp)));
  33. 33. - Using PL/SQL in SQL- Create script based on the table dataUsing the table function
  34. 34. • 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);
  35. 35. SQLstatementSELECT insert into DEPT( LOC, DNAME, DEPTNO) values( ||LOC||, ||DNAME||, ||DEPTNO||); lineFROM DEPT;• Using SQLCreate script based on the table data
  36. 36. SELECT *FROM table(createinsertscriptfor(DEPT));SQLstatement• Using table functionsCreate script based on the table data
  37. 37. • Using table functions• Hide complexity behind PL/SQLinterface• Don’t worry about datatypesCreate script based on the table data
  38. 38. Overview of Table FunctionsTable Function ConceptsReturn collection, query like tablePipelinedParallelUsingTable FunctionsUse PL/SQL in SQLHide complexityTable functions
  39. 39. 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

×