Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

22
Using SQL in PL/SQL Using SQL in PL/SQL Oracle Database PL/SQL 10g Oracle Database PL/SQL 10g Programming Programming Chapter 4 Chapter 4

description

Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming. Chapter 4. Using SQL in PL/SQL. Using SQL Statements Using SQL Built-in Functions Using Pseudo Columns Using Cursors Dynamic SQL Statements Regular Expressions. Using SQL in PL/SQL SQL Command Types. - PowerPoint PPT Presentation

Transcript of Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

Page 1: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

Using SQL in PL/SQLUsing SQL in PL/SQLOracle Database PL/SQL 10g Oracle Database PL/SQL 10g

ProgrammingProgramming

Chapter 4Chapter 4

Page 2: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 22

Using SQL in PL/SQLUsing SQL in PL/SQL

Using SQL StatementsUsing SQL Statements Using SQL Built-in FunctionsUsing SQL Built-in Functions Using Pseudo Columns Using Pseudo Columns Using CursorsUsing Cursors Dynamic SQL StatementsDynamic SQL Statements Regular ExpressionsRegular Expressions

Page 3: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 33

Using SQL in PL/SQLUsing SQL in PL/SQL

SQL Command TypesSQL Command Types Data Control Language (DCL)Data Control Language (DCL) command command

can be used directly inside PL/SQL.can be used directly inside PL/SQL. Data Manipulation Language (DML)Data Manipulation Language (DML)

commands can be used directly inside commands can be used directly inside PL/SQL blocks.PL/SQL blocks.

Data Definition Language (DDL)Data Definition Language (DDL) commands cannot be used directly inside commands cannot be used directly inside PL/SQL blocks, but they can be used PL/SQL blocks, but they can be used indirectly through dynamic SQL statements.indirectly through dynamic SQL statements.

Page 4: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 44

Using SQL in PL/SQLUsing SQL in PL/SQL

SQL Command Types: SQL Command Types: DCLDCL

Single DML statements are an all or nothing Single DML statements are an all or nothing proposition, known as proposition, known as autonomousautonomous transactions: transactions: You type COMMIT to accept a DML SQL statement.You type COMMIT to accept a DML SQL statement. You type ROLLBACK to reject a DML SQL statement.You type ROLLBACK to reject a DML SQL statement.

Two or more DML statements as a set of activities Two or more DML statements as a set of activities can act as autonomously but can be controlled as can act as autonomously but can be controlled as groups using DCL commands; and these are known groups using DCL commands; and these are known as as transactionstransactions, not , not autonomous transactions:autonomous transactions: A transaction requires that all DML statements succeed or A transaction requires that all DML statements succeed or

fail.fail. A transaction is ACID compliant and has four properties: A transaction is ACID compliant and has four properties:

Atomic, Consistent, Isolated, and Durable.Atomic, Consistent, Isolated, and Durable.

Page 5: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 55

Using SQL in PL/SQLUsing SQL in PL/SQL

SQL Command Types: SQL Command Types: DCLDCL

SAVEPOINTSAVEPOINT sets a named transaction marker. sets a named transaction marker. COMMITCOMMIT makes permanent any changes makes permanent any changes

made by a user during a session.made by a user during a session. ROLLBACKROLLBACK undoes any changes made by a undoes any changes made by a

user:user: To the beginning of session when the command To the beginning of session when the command

does not refer to a does not refer to a SAVEPOINTSAVEPOINT; which models ; which models autonomous transactions.autonomous transactions.

To the named To the named SAVEPOINTSAVEPOINT provided as an actual provided as an actual parameter to the parameter to the ROLLBACKROLLBACK command; which command; which models transactions.models transactions.

Page 6: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 66

Using SQL in PL/SQLUsing SQL in PL/SQLSQL Command Types: Autonomous SQL Command Types: Autonomous

TransactionsTransactions

BEGINBEGIN UPDATE a_tableUPDATE a_table SET name = 'Autonomous'SET name = 'Autonomous' WHERE id = 1;WHERE id = 1;EXCEPTIONEXCEPTION WHEN others THENWHEN others THEN ROLLBACK;ROLLBACK;END;END;//

Page 7: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 77

Using SQL in PL/SQLUsing SQL in PL/SQL SQL Command Types: Transactions SQL Command Types: Transactions

BEGINBEGIN SAVEPOINT beginningSAVEPOINT beginning; ; INSERT INTO parent_tableINSERT INTO parent_table VALUES (parent_id, name);VALUES (parent_id, name); INSERT INTO child_tableINSERT INTO child_table VALUES (child_id, parent_id, name);VALUES (child_id, parent_id, name); COMMIT;COMMIT;EXCEPTIONEXCEPTION WHEN others THENWHEN others THEN ROLLBACK TO beginning;ROLLBACK TO beginning;END;END;//

Page 8: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 88

Using SQL in PL/SQLUsing SQL in PL/SQL SQL Command Types: Transactions SQL Command Types: Transactions

SET TRANSACTION READ ONLYSET TRANSACTION READ ONLY Constrains the transaction scope of action, which is useful when Constrains the transaction scope of action, which is useful when

working in snapshot databases.working in snapshot databases. SET TRANSACTION READ WRITESET TRANSACTION READ WRITE

The default state frees the transaction to write data.The default state frees the transaction to write data. SET TRANSACTION ISOLATION LEVEL READ COMMITTEDSET TRANSACTION ISOLATION LEVEL READ COMMITTED

Constrains the transaction scope of action, requiring all pending Constrains the transaction scope of action, requiring all pending transactions to wait on any locked row.transactions to wait on any locked row.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLESET TRANSACTION ISOLATION LEVEL SERIALIZABLE Constrains the transaction scope of action, requiring all pending Constrains the transaction scope of action, requiring all pending

transactions to abort when encountering locked rows.transactions to abort when encountering locked rows. SET TRANSACTION USE ROLLBACK SEGMENTSET TRANSACTION USE ROLLBACK SEGMENT

Constrains the transaction to a named ROLLBACK segment, which Constrains the transaction to a named ROLLBACK segment, which enables you to target large transactions to large ROLLBACK enables you to target large transactions to large ROLLBACK segments, but this is not generally used when you’re using segments, but this is not generally used when you’re using automatic undo management.automatic undo management.

Page 9: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 99

Using SQL in PL/SQLUsing SQL in PL/SQL SQL Command Types: Query Locking SQL Command Types: Query Locking

RowsRowsDECLAREDECLARE CURSOR c ISCURSOR c IS SELECT * FROM a_tableSELECT * FROM a_table FOR UPDATE [NOWAIT];FOR UPDATE [NOWAIT]; -- NOWAIT aborts for locked rows. -- NOWAIT aborts for locked rows.BEGINBEGIN FOR i IN c LOOPFOR i IN c LOOP processing_statement;processing_statement; END LOOP;END LOOP;END;END;//

Page 10: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1010

Using SQL in PL/SQLUsing SQL in PL/SQL

SQL Built-in FunctionsSQL Built-in Functions PL/SQL supports SQL built-in functions, PL/SQL supports SQL built-in functions,

and they can be used:and they can be used: In SQL statements inside PL/SQL blocks.In SQL statements inside PL/SQL blocks. In PL/SQL statements and against PL/SQL In PL/SQL statements and against PL/SQL

variables.variables. SQL built-in functions are qualified in the SQL built-in functions are qualified in the STANDARDSTANDARD package owned by the package owned by the SYSSYS user. user.

The The STANDARDSTANDARD package addresses package addresses DATEDATE, , NUMBERNUMBER and and VARCHAR2VARCHAR2 data types. data types.

The The DBMS_LOBDBMS_LOB package addresses package addresses LOBLOB data data types.types.

Page 11: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1111

Using SQL in PL/SQLUsing SQL in PL/SQLPseudo Columns: Pseudo Columns: ROWIDROWID and and ROWNUMROWNUM

ROWIDROWID is a pseudo column that contains is a pseudo column that contains the physical block address to a row.the physical block address to a row.

ROWNUMROWNUM is a pseudo column that is a pseudo column that contains the number of rows processed contains the number of rows processed by an explicit cursor, which is the by an explicit cursor, which is the number of rows, which are selected number of rows, which are selected from a table.from a table.

ROWNUMROWNUM pseudo column can get Top-N pseudo column can get Top-N SQL query results.SQL query results.

Page 12: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1212

Using SQL in PL/SQLUsing SQL in PL/SQLPseudo Columns: Pseudo Columns: SQL%ROWCOUNTSQL%ROWCOUNT

SQL%ROWCOUNTSQL%ROWCOUNT is a cursor attribute is a cursor attribute that contains the number of rows that contains the number of rows processed by any SQL statement, processed by any SQL statement, like when you:like when you: Insert rows into a table.Insert rows into a table. Update rows in a table.Update rows in a table. Delete rows from a table.Delete rows from a table. Selecte rows from a table.Selecte rows from a table.

Page 13: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1313

Using SQL in PL/SQLUsing SQL in PL/SQL

Using CursorsUsing Cursors All DML statements (All DML statements (INSERTINSERT, , UPDATEUPDATE and and DELETEDELETE) )

inside PL/SQL blocks are implicit cursors.inside PL/SQL blocks are implicit cursors. All DQL statements are implicit or explicit cursors:All DQL statements are implicit or explicit cursors:

Implicit DQL statements are not defined in the declaration Implicit DQL statements are not defined in the declaration section.section.

Explicit DQL statements are defined in the declaration section.Explicit DQL statements are defined in the declaration section. Cursors are copies of stored data in private work Cursors are copies of stored data in private work

areas.areas. All system reference cursors are explicit cursors that All system reference cursors are explicit cursors that

are:are: Strongly typed, or reference a catalog object.Strongly typed, or reference a catalog object. Weakly typed, or do not reference a catalog object.Weakly typed, or do not reference a catalog object. Capable of being passed as parameters to subroutines.Capable of being passed as parameters to subroutines. Capable of being returned values from subroutines.Capable of being returned values from subroutines.

Page 14: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1414

Using SQL in PL/SQL Using SQL in PL/SQL Catalog Types: Implicit CursorCatalog Types: Implicit Cursor

BEGINBEGIN FORFOR i i ININ (SELECT id, name FROM a_table) (SELECT id, name FROM a_table) LOOPLOOP dbms_output.put_line('ID: ['||dbms_output.put_line('ID: ['||i.idi.id||']');||']'); dbms_output.put_line('Name: ['||dbms_output.put_line('Name: ['||i.namei.name||']');||']'); END LOOP;END LOOP;END;END;//

Page 15: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1515

Using SQL in PL/SQL Using SQL in PL/SQL Catalog Types: Explicit CursorCatalog Types: Explicit Cursor

DECLAREDECLARE

CURSORCURSOR c (id_in NUMBER) c (id_in NUMBER) ISIS

SELECT id, name FROM a_table WHERE id = id_in;SELECT id, name FROM a_table WHERE id = id_in;

BEGINBEGIN

FORFOR i i ININ c c LOOPLOOP

dbms_output.put_line('ID: ['||dbms_output.put_line('ID: ['||i.idi.id||']');||']');

dbms_output.put_line('Name: ['||dbms_output.put_line('Name: ['||i.namei.name||']');||']');

END LOOP;END LOOP;

END;END;

//

Page 16: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1616

Using SQL in PL/SQL Using SQL in PL/SQL Catalog Types: Explicit CursorCatalog Types: Explicit Cursor

DECLAREDECLARE

a_name VARCHAR2(10);a_name VARCHAR2(10);

CURSORCURSOR c c ISIS SELECT name FROM a_table; SELECT name FROM a_table;

BEGINBEGIN

OPENOPEN c; c;

LOOPLOOP

FETCHFETCH c c INTOINTO a_number; a_number;

EXIT WHENEXIT WHEN c%NOTFOUND; c%NOTFOUND;

dbms_output.put_line('Name: ['||a_name||']');dbms_output.put_line('Name: ['||a_name||']');

END LOOP;END LOOP;

CLOSECLOSE c; c;

END;END;

//

Page 17: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1717

Using SQL in PL/SQL Using SQL in PL/SQL Catalog Types: Strongly Typed Reference Catalog Types: Strongly Typed Reference

CursorCursor

DECLAREDECLARE TYPE TYPE strong_cursorstrong_cursor IS REF CURSOR IS REF CURSOR RETURN a_table%ROWTYPERETURN a_table%ROWTYPE;; cursor_variablecursor_variable STRONG_CURSORSTRONG_CURSOR;; rowrow a_table%ROWTYPEa_table%ROWTYPE;;BEGINBEGIN OPENOPEN cursor_variablecursor_variable FORFOR SELECT * FROM a_table;SELECT * FROM a_table; LOOPLOOP FETCHFETCH cursor_variablecursor_variable INTOINTO rowrow;; EXIT WHENEXIT WHEN cursor_variable%NOTFOUNDcursor_variable%NOTFOUND;; dbms_output.put_line('Print ['||dbms_output.put_line('Print ['||row.namerow.name||']');||']'); END LOOP;END LOOP; CLOSECLOSE cursor_variablecursor_variable;;END;END;//

Page 18: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1818

Using SQL in PL/SQL Using SQL in PL/SQL Catalog Types: Weakly Typed Reference Catalog Types: Weakly Typed Reference

CursorCursor

DECLAREDECLARE TYPE TYPE weak_cursorweak_cursor IS REF CURSOR; IS REF CURSOR; cursor_variablecursor_variable WEAK_CURSORWEAK_CURSOR;; rowrow a_table%ROWTYPEa_table%ROWTYPE;;BEGINBEGIN OPENOPEN cursor_variablecursor_variable FORFOR SELECT * FROM a_table;SELECT * FROM a_table; LOOPLOOP FETCHFETCH cursor_variablecursor_variable INTOINTO rowrow;; EXIT WHENEXIT WHEN cursor_variable%NOTFOUNDcursor_variable%NOTFOUND;; dbms_output.put_line('Print ['||dbms_output.put_line('Print ['||row.namerow.name||']');||']'); END LOOP;END LOOP; CLOSECLOSE cursor_variablecursor_variable;;END;END;//

Page 19: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 1919

Using SQL in PL/SQLUsing SQL in PL/SQL

Dynamic SQL StatementsDynamic SQL Statements Dynamic SQL statements are executed as Dynamic SQL statements are executed as

autonomous transactions, natively in a autonomous transactions, natively in a SQL*Plus subshell.SQL*Plus subshell.

Dynamic SQL statements provide the Dynamic SQL statements provide the means to run DDL statements in PL/SQL means to run DDL statements in PL/SQL blocks, provided they don’t alter a table blocks, provided they don’t alter a table referenced in the same block.referenced in the same block.

Dynamic SQL is also known as NDS, which Dynamic SQL is also known as NDS, which stands for stands for Native Dynamic SQLNative Dynamic SQL..

Page 20: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 2020

Using SQL in PL/SQL Using SQL in PL/SQL

Regular ExpressionsRegular Expressions REGEXP_LIKE()REGEXP_LIKE()

Enables regular expression searches of character Enables regular expression searches of character strings.strings.

REGEXP_INSTR()REGEXP_INSTR() Enables regular expression searches to locate a Enables regular expression searches to locate a

position in a string.position in a string. REGEXP_REPLACE()REGEXP_REPLACE()

Enables regular expression search and replace actions.Enables regular expression search and replace actions. REGEXP_SUBSTR()REGEXP_SUBSTR()

Enables regular expression searches to locate a Enables regular expression searches to locate a substring in a string.substring in a string.

Page 21: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 2121

Using SQL in PL/SQL Using SQL in PL/SQL Regular Expressions: Regular Expressions:

MetacharactersMetacharacters ** Matches zero or more characters.Matches zero or more characters. .. A valid character.A valid character. ^̂ Begins pattern matching from beginning of a line.Begins pattern matching from beginning of a line. [][] Groups characters, treats them as by a logical OR Groups characters, treats them as by a logical OR

operation.operation. $$ Ends pattern matching at the end of the line.Ends pattern matching at the end of the line. \\ Escape character back quotes a special Escape character back quotes a special

character, character, signaling it should be treated as an ordinary signaling it should be treated as an ordinary one.one.

()() Groups strings, which are delimited by a | Groups strings, which are delimited by a | symbol.symbol.

\\ Escape character back quotes a special Escape character back quotes a special character, character, signaling it should be treated as an ordinary signaling it should be treated as an ordinary one.one.

Page 22: Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming

20062006 Oracle Database PL/SQL 10g Programming Oracle Database PL/SQL 10g Programming

(Chapter 4)(Chapter 4) Page Page 2222

SummarySummary

Using SQL StatementsUsing SQL Statements Using SQL Built-in FunctionsUsing SQL Built-in Functions Using Pseudo Columns Using Pseudo Columns Using CursorsUsing Cursors Dynamic SQL StatementsDynamic SQL Statements Regular ExpressionsRegular Expressions