Oracle Database Notes for Professionals (GoalKicker Books) (Z Library)

Author: GoalKicker Books

其他

This Oracle® Database Notes for Professionals book is compiled from Stack Overflow Documentation , the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Oracle® Database group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners.

📄 File Format: PDF
💾 File Size: 1.2 MB
313
Views
121
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Oracle Database Notes for ProfessionalsOracle® Database Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Oracle® Database group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 100+ pages of professional hints and tricks
📄 Page 2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Oracle Database 2 ....................................................................................... Section 1.1: Hello World 2 ................................................................................................................................................. Section 1.2: SQL Query 2 .................................................................................................................................................. Section 1.3: Hello world! from table 2 .............................................................................................................................. Section 1.4: Hello World from PL/SQL 3 ......................................................................................................................... Chapter 2: Getting started with PL/SQL 4 ........................................................................................................... Section 2.1: Hello World 4 ................................................................................................................................................. Section 2.2: Definition of PL/SQL 4 ................................................................................................................................. Section 2.3: Dierence between %TYPE and %ROWTYPE 5 ........................................................................................ Section 2.4: Create or replace a view 6 .......................................................................................................................... Section 2.5: Create a table 6 ........................................................................................................................................... Section 2.6: About PL/SQL 6 ........................................................................................................................................... Chapter 3: Anonymous PL/SQL Block 8 ................................................................................................................ Section 3.1: An example of an anonymous block 8 ....................................................................................................... Chapter 4: PL/SQL procedure 9 ............................................................................................................................... Section 4.1: Syntax 9 ......................................................................................................................................................... Section 4.2: Hello World 9 ................................................................................................................................................ Section 4.3: In/Out Parameters 9 ................................................................................................................................... Chapter 5: Data Dictionary 11 ................................................................................................................................... Section 5.1: Describes all objects in the database 11 ................................................................................................... Section 5.2: To see all the data dictionary views to which you have access 11 ........................................................ Section 5.3: Text source of the stored objects 11 ......................................................................................................... Section 5.4: Get list of all tables in Oracle 11 ................................................................................................................. Section 5.5: Privilege information 11 .............................................................................................................................. Section 5.6: Oracle version 12 ......................................................................................................................................... Chapter 6: Dates 13 ......................................................................................................................................................... Section 6.1: Date Arithmetic - Dierence between Dates in Days, Hours, Minutes and/or Seconds 13 ................. Section 6.2: Setting the Default Date Format Model 14 ............................................................................................... Section 6.3: Date Arithmetic - Dierence between Dates in Months or Years 14 ...................................................... Section 6.4: Extract the Year, Month, Day, Hour, Minute or Second Components of a Date 15 .............................. Section 6.5: Generating Dates with No Time Component 16 ....................................................................................... Section 6.6: Generating Dates with a Time Component 16 ......................................................................................... Section 6.7: The Format of a Date 17 ............................................................................................................................. Section 6.8: Converting Dates to a String 17 ................................................................................................................. Section 6.9: Changing How SQL/Plus or SQL Developer Display Dates 18 ............................................................... Section 6.10: Time Zones and Daylight Savings Time 18 ............................................................................................. Section 6.11: Leap Seconds 19 ......................................................................................................................................... Section 6.12: Getting the Day of the Week 19 ............................................................................................................... Chapter 7: Working with Dates 20 ........................................................................................................................... Section 7.1: Date Arithmetic 20 ........................................................................................................................................ Section 7.2: Add_months function 20 ............................................................................................................................ Chapter 8: DUAL table 22 ............................................................................................................................................. Section 8.1: The following example returns the current operating system date and time 22 .................................. Section 8.2: The following example generates numbers between start_value and end_value 22 ........................ Chapter 9: JOINS 23 .........................................................................................................................................................
📄 Page 3
Section 9.1: CROSS JOIN 23 ............................................................................................................................................. Section 9.2: LEFT OUTER JOIN 24 .................................................................................................................................. Section 9.3: RIGHT OUTER JOIN 25 ................................................................................................................................ Section 9.4: FULL OUTER JOIN 27 .................................................................................................................................. Section 9.5: ANTIJOIN 28 ................................................................................................................................................. Section 9.6: INNER JOIN 29 ............................................................................................................................................. Section 9.7: JOIN 30 ......................................................................................................................................................... Section 9.8: SEMIJOIN 30 ................................................................................................................................................. Section 9.9: NATURAL JOIN 31 ....................................................................................................................................... Chapter 10: Handling NULL values 33 .................................................................................................................... Section 10.1: Operations containing NULL are NULL, except concatenation 33 ........................................................ Section 10.2: NVL2 to get a dierent result if a value is null or not 33 ....................................................................... Section 10.3: COALESCE to return the first non-NULL value 33 ................................................................................... Section 10.4: Columns of any data type can contain NULLs 33 .................................................................................. Section 10.5: Empty strings are NULL 33 ....................................................................................................................... Section 10.6: NVL to replace null value 34 ..................................................................................................................... Chapter 11: String Manipulation 35 ........................................................................................................................... Section 11.1: INITCAP 35 .................................................................................................................................................... Section 11.2: Regular expression 35 ................................................................................................................................ Section 11.3: SUBSTR 35 ................................................................................................................................................... Section 11.4: Concatenation: Operator || or concat() function 36 ................................................................................ Section 11.5: UPPER 36 ...................................................................................................................................................... Section 11.6: LOWER 37 .................................................................................................................................................... Section 11.7: LTRIM / RTRIM 37 ....................................................................................................................................... Chapter 12: IF-THEN-ELSE Statement 38 .............................................................................................................. Section 12.1: IF-THEN 38 ................................................................................................................................................... Section 12.2: IF-THEN-ELSE 38 ........................................................................................................................................ Section 12.3: IF-THEN-ELSIF-ELSE 38 .............................................................................................................................. Chapter 13: Limiting the rows returned by a query (Pagination) 39 ...................................................... Section 13.1: Get first N rows with row limiting clause 39 .............................................................................................. Section 13.2: Get row N through M from many rows (before Oracle 12c) 39 ............................................................. Section 13.3: Get N numbers of Records from table 39 ................................................................................................ Section 13.4: Skipping some rows then taking some 40 ............................................................................................... Section 13.5: Skipping some rows from result 40 .......................................................................................................... Section 13.6: Pagination in SQL 40 .................................................................................................................................. Chapter 14: Recursive Sub-Query Factoring using the WITH Clause (A.K.A. Common Table Expressions) 42 ..................................................................................................................................................... Section 14.1: Splitting a Delimited String 42 .................................................................................................................... Section 14.2: A Simple Integer Generator 42 .................................................................................................................. Chapter 15: Dierent ways to update records 44 ........................................................................................... Section 15.1: Update using Merge 44 .............................................................................................................................. Section 15.2: Update Syntax with example 44 ............................................................................................................... Section 15.3: Update Using Inline View 44 ...................................................................................................................... Section 15.4: Merge with sample data 45 ....................................................................................................................... Chapter 16: Update with Joins 47 ............................................................................................................................. Section 16.1: Examples: what works and what doesn't 47 ............................................................................................. Chapter 17: Functions 49 ............................................................................................................................................... Section 17.1: Calling Functions 49 .................................................................................................................................... Chapter 18: Statistical functions 50 .........................................................................................................................
📄 Page 4
Section 18.1: Calculating the median of a set of values 50 ........................................................................................... Chapter 19: Window Functions 51 ............................................................................................................................. Section 19.1: Ratio_To_Report 51 ................................................................................................................................... Chapter 20: Creating a Context 52 .......................................................................................................................... Section 20.1: Create a Context 52 ................................................................................................................................... Chapter 21: Splitting Delimited Strings 53 ............................................................................................................ Section 21.1: Splitting Strings using a Hierarchical Query 53 ........................................................................................ Section 21.2: Splitting Strings using a PL/SQL Function 53 .......................................................................................... Section 21.3: Splitting Strings using a Recursive Sub-query Factoring Clause 54 ..................................................... Section 21.4: Splitting Strings using a Correlated Table Expression 55 ...................................................................... Section 21.5: Splitting Strings using CROSS APPLY (Oracle 12c) 56 ............................................................................. Section 21.6: Splitting Strings using XMLTable and FLWOR expressions 57 .............................................................. Section 21.7: Splitting Delimited Strings using XMLTable 57 ........................................................................................ Chapter 22: Collections and Records 59 ............................................................................................................... Section 22.1: Use a collection as a return type for a split function 59 ........................................................................ Chapter 23: Object Types 60 ....................................................................................................................................... Section 23.1: Accessing stored objects 60 ...................................................................................................................... Section 23.2: BASE_TYPE 60 ........................................................................................................................................... Section 23.3: MID_TYPE 61 .............................................................................................................................................. Section 23.4: LEAF_TYPE 62 ............................................................................................................................................ Chapter 24: Loop 64 ........................................................................................................................................................ Section 24.1: Simple Loop 64 ........................................................................................................................................... Section 24.2: WHILE Loop 64 ........................................................................................................................................... Section 24.3: FOR Loop 64 ............................................................................................................................................... Chapter 25: Cursors 67 ................................................................................................................................................... Section 25.1: Parameterized "FOR loop" Cursor 67 ...................................................................................................... Section 25.2: Implicit "FOR loop" cursor 67 ................................................................................................................... Section 25.3: Handling a CURSOR 67 ............................................................................................................................. Section 25.4: Working with SYS_REFCURSOR 68 ......................................................................................................... Chapter 26: Sequences 69 ............................................................................................................................................ Section 26.1: Creating a Sequence: Example 69 ............................................................................................................ Chapter 27: Indexes 71 ................................................................................................................................................... Section 27.1: b-tree index 71 ............................................................................................................................................ Section 27.2: Bitmap Index 71 ......................................................................................................................................... Section 27.3: Function Based Index 71 ........................................................................................................................... Chapter 28: Hints 72 ........................................................................................................................................................ Section 28.1: USE_NL 72 .................................................................................................................................................. Section 28.2: APPEND HINT 72 ........................................................................................................................................ Section 28.3: Parallel Hint 72 ........................................................................................................................................... Section 28.4: USE_HASH 73 ............................................................................................................................................ Section 28.5: FULL 73 ....................................................................................................................................................... Section 28.6: Result Cache 74 ......................................................................................................................................... Chapter 29: Packages 75 ............................................................................................................................................... Section 29.1: Define a Package header and body with a function 75 ......................................................................... Section 29.2: Overloading 75 .......................................................................................................................................... Section 29.3: Package Usage 76 ..................................................................................................................................... Chapter 30: Exception Handling 78 .......................................................................................................................... Section 30.1: Syntax 78 .....................................................................................................................................................
📄 Page 5
Section 30.2: User defined exceptions 78 ...................................................................................................................... Section 30.3: Internally defined exceptions 79 .............................................................................................................. Section 30.4: Predefined exceptions 80 .......................................................................................................................... Section 30.5: Define custom exception, raise it and see where it comes from 81 ..................................................... Section 30.6: Handling connexion error exceptions 82 ................................................................................................ Section 30.7: Exception handling 83 ............................................................................................................................... Chapter 31: Error logging 84 ........................................................................................................................................ Section 31.1: Error logging when writing to database 84 .............................................................................................. Chapter 32: Database Links 85 .................................................................................................................................. Section 32.1: Creating a database link 85 ...................................................................................................................... Section 32.2: Create Database Link 85 .......................................................................................................................... Chapter 33: Table partitioning 87 ............................................................................................................................. Section 33.1: Select existing partitions 87 ....................................................................................................................... Section 33.2: Drop partition 87 ........................................................................................................................................ Section 33.3: Select data from a partition 87 ................................................................................................................ Section 33.4: Split Partition 87 ......................................................................................................................................... Section 33.5: Merge Partitions 87 .................................................................................................................................... Section 33.6: Exchange a partition 87 ............................................................................................................................ Section 33.7: Hash partitioning 88 .................................................................................................................................. Section 33.8: Range partitioning 88 ................................................................................................................................ Section 33.9: List partitioning 88 ..................................................................................................................................... Section 33.10: Truncate a partition 89 ............................................................................................................................ Section 33.11: Rename a partition 89 .............................................................................................................................. Section 33.12: Move partition to dierent tablespace 89 ............................................................................................. Section 33.13: Add new partition 89 ................................................................................................................................ Chapter 34: Oracle Advanced Queuing (AQ) 90 ................................................................................................ Section 34.1: Simple Producer/Consumer 90 ................................................................................................................. Chapter 35: constraints 94 ........................................................................................................................................... Section 35.1: Update foreign keys with new value in Oracle 94 .................................................................................. Section 35.2: Disable all related foreign keys in oracle 94 .......................................................................................... Chapter 36: Autonomous Transactions 95 ........................................................................................................... Section 36.1: Using autonomous transaction for logging errors 95 ............................................................................ Chapter 37: Oracle MAF 96 ........................................................................................................................................... Section 37.1: To get value from Binding 96 .................................................................................................................... Section 37.2: To set value to binding 96 ......................................................................................................................... Section 37.3: To invoke a method from binding 96 ...................................................................................................... Section 37.4: To call a javaScript function 96 ................................................................................................................ Chapter 38: level query 97 ........................................................................................................................................... Section 38.1: Generate N Number of records 97 ........................................................................................................... Section 38.2: Few usages of Level Query 97 ................................................................................................................. Chapter 39: Hierarchical Retrieval With Oracle Database 12C 98 ........................................................... Section 39.1: Using the CONNECT BY Caluse 98 ............................................................................................................ Section 39.2: Specifying the Direction of the Query From the Top Down 98 ............................................................ Chapter 40: Data Pump 99 .......................................................................................................................................... Section 40.1: Monitor Datapump jobs 99 ....................................................................................................................... Section 40.2: Step 3/6 : Create directory 99 .................................................................................................................. Section 40.3: Step 7 : Export Commands 99 .................................................................................................................. Section 40.4: Step 9 : Import Commands 100 ............................................................................................................... Section 40.5: Datapump steps 101 .................................................................................................................................
📄 Page 6
Section 40.6: Copy tables between dierent schemas and tablespaces 101 ........................................................... Chapter 41: Bulk collect 102 ........................................................................................................................................ Section 41.1: Bulk data Processing 102 ........................................................................................................................... Chapter 42: Real Application Security 103 .......................................................................................................... Section 42.1: Application 103 ........................................................................................................................................... Chapter 43: Assignments model and language 105 ....................................................................................... Section 43.1: Assignments model in PL/SQL 105 .......................................................................................................... Chapter 44: Triggers 107 .............................................................................................................................................. Section 44.1: Before INSERT or UPDATE trigger 107 .................................................................................................... Chapter 45: Dynamic SQL 108 .................................................................................................................................... Section 45.1: Select value with dynamic SQL 108 .......................................................................................................... Section 45.2: Insert values in dynamic SQL 108 ............................................................................................................ Section 45.3: Update values in dynamic SQL 108 ......................................................................................................... Section 45.4: Execute DDL statement 109 ..................................................................................................................... Section 45.5: Execute anonymous block 109 ................................................................................................................ Credits 110 ............................................................................................................................................................................ You may also like 112 ......................................................................................................................................................
📄 Page 7
GoalKicker.com – Oracle® Database Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/OracleDatabaseBook This Oracle® Database Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Oracle® Database group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
📄 Page 8
GoalKicker.com – Oracle® Database Notes for Professionals 2 Chapter 1: Getting started with Oracle Database Version Release Date Version 1 (unreleased) 1978-01-01 Oracle V2 1979-01-01 Oracle Version 3 1983-01-01 Oracle Version 4 1984-01-01 Oracle Version 5 1985-01-01 Oracle Version 6 1988-01-01 Oracle7 1992-01-01 Oracle8 1997-07-01 Oracle8i 1999-02-01 Oracle9i 2001-06-01 Oracle 10g 2003-01-01 Oracle 11g 2007-01-01 Oracle 12c 2013-01-01 Section 1.1: Hello World SELECT 'Hello world!' FROM dual; In Oracle's flavor of SQL, "dual is just a convienence table". It was originally intended to double rows via a JOIN, but now contains one row with a DUMMY value of 'X'. Section 1.2: SQL Query List employees earning more than $50000 born this century. List their name, date of birth and salary, sorted alphabetically by name. SELECT employee_name, date_of_birth, salary FROM employees WHERE salary > 50000 AND date_of_birth >= DATE '2000-01-01' ORDER BY employee_name; Show the number of employees in each department with at least 5 employees. List the largest departments first. SELECT department_id, COUNT(*) FROM employees GROUP BY department_id HAVING COUNT(*) >= 5 ORDER BY COUNT(*) DESC; Section 1.3: Hello world! from table Create a simple table CREATE TABLE MY_table ( what VARCHAR2(10), who VARCHAR2(10),
📄 Page 9
GoalKicker.com – Oracle® Database Notes for Professionals 3 mark VARCHAR2(10) ); Insert values (you can omit target columns if you provide values for all columns) INSERT INTO my_table (what, who, mark) VALUES ('Hello', 'world', '!' ); INSERT INTO my_table VALUES ('Bye bye', 'ponies', '?' ); INSERT INTO my_table (what) VALUES('Hey'); Remember to commit, because Oracle uses transactions COMMIT; Select your data: SELECT what, who, mark FROM my_table WHERE what='Hello'; Section 1.4: Hello World from PL/SQL /* PL/SQL is a core Oracle Database technology, allowing you to build clean, secure, optimized APIs to SQL and business logic. */ SET serveroutput ON BEGIN DBMS_OUTPUT.PUT_LINE ('Hello World!'); END;
📄 Page 10
GoalKicker.com – Oracle® Database Notes for Professionals 4 Chapter 2: Getting started with PL/SQL Section 2.1: Hello World SET serveroutput ON DECLARE message CONSTANT VARCHAR2(32767):= 'Hello, World!'; BEGIN DBMS_OUTPUT.put_line(message); END; / Command SET serveroutput ON is required in SQL*Plus and SQL Developer clients to enable the output of DBMS_OUTPUT. Without the command nothing is displayed. The END; line signals the end of the anonymous PL/SQL block. To run the code from SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at SQL prompt, it produces the following result: Hello, World! PL/SQL procedure successfully completed. Section 2.2: Definition of PL/SQL PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 7), TimesTen in-memory database (since version 11.2.1), and IBM DB2 (since version 9.7). The basic unit in PL/SQL is called a block, which is made up of three parts: a declarative part, an executable part, and an exception-building part. DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <EXCEPTION handling> END; Declarations - This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program. Executable Commands - This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed. Exception Handling - This section starts with the keyword EXCEPTION. This section is again optional and contains exception(s) that handle errors in the program. Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END.
📄 Page 11
GoalKicker.com – Oracle® Database Notes for Professionals 5 In anonymous block, only executable part of block is required, other parts are not nessesary. Below is example of simple anonymous code, which does not do anything but perform without error reporting. BEGIN NULL; END; / Missing excecutable instruction leads to an error, becouse PL/SQL does not support empty blocks. For example, excecution of code below leads to an error: BEGIN END; / Application will raise error: END; * ERROR AT line 2: ORA-06550: line 2, column 1: PLS-00103: Encountered the symbol "END" WHEN expecting one OF the following: ( BEGIN CASE DECLARE EXIT FOR GOTO IF LOOP MOD NULL PRAGMA RAISE RETURN SELECT UPDATE WHILE WITH <an identifier> <a double-quoted delimited-identifier> <a bind variable> << continue CLOSE CURRENT DELETE FETCH LOCK INSERT OPEN ROLLBACK SAVEPOINT SET SQL EXECUTE COMMIT FORALL MERGE pipe purge Symbol " * " in line below keyword "END;" means, that the block which ends with this block is empty or bad constructed. Every execution block needs instructions to do, even if it does nothing, like in our example. Section 2.3: Dierence between %TYPE and %ROWTYPE %TYPE: Used to declare a field with the same type as that of a specified table's column. DECLARE vEmployeeName Employee.Name%TYPE; BEGIN SELECT Name INTO vEmployeeName FROM Employee WHERE ROWNUM = 1; DBMS_OUTPUT.PUT_LINE(vEmployeeName); END; / %ROWTYPE: Used to declare a record with the same types as found in the specified table, view or cursor (= multiple columns). DECLARE rEmployee Employee%ROWTYPE; BEGIN rEmployee.Name := 'Matt'; rEmployee.Age := 31; DBMS_OUTPUT.PUT_LINE(rEmployee.Name);
📄 Page 12
GoalKicker.com – Oracle® Database Notes for Professionals 6 DBMS_OUTPUT.PUT_LINE(rEmployee.Age); END; / Section 2.4: Create or replace a view In this example we are going to create a view. A view is mostly used as a simple way of fetching data from multiple tables. Example 1: View with a select on one table. CREATE OR REPLACE VIEW LessonView AS SELECT L.* FROM Lesson L; Example 2: View with a select on multiple tables. CREATE OR REPLACE VIEW ClassRoomLessonView AS SELECT C.Id, C.Name, L.Subject, L.Teacher FROM ClassRoom C, Lesson L WHERE C.Id = L.ClassRoomId; To call this views in a query you can use a select statement. SELECT * FROM LessonView; SELECT * FROM ClassRoomLessonView; Section 2.5: Create a table Below we are going to create a table with 3 columns. The column Id must be filled is, so we define it NOT NULL. On the column Contract we also add a check so that the only value allowed is 'Y' or 'N'. If an insert in done and this column is not specified during the insert then default a 'N' is inserted. CREATE TABLE Employee ( Id NUMBER NOT NULL, Name VARCHAR2(60), Contract CHAR DEFAULT 'N' NOT NULL, --- CONSTRAINT p_Id PRIMARY KEY(Id), CONSTRAINT c_Contract CHECK (Contract IN('Y','N')) ); Section 2.6: About PL/SQL PL/SQL stands for Procedural Language extensions to SQL. PL/SQL is available only as an "enabling technology" within other software products; it does not exist as a standalone language. You can use PL/SQL in the Oracle relational database, in the Oracle Server, and in client-side application development tools, such as Oracle Forms. Here are some of the ways you might use PL/SQL:
📄 Page 13
GoalKicker.com – Oracle® Database Notes for Professionals 7 To build stored procedures. .1. To create database triggers.2. To implement client-side logic in your Oracle Forms application.3. To link a World Wide Web home page to an Oracle database.4.
📄 Page 14
GoalKicker.com – Oracle® Database Notes for Professionals 8 Chapter 3: Anonymous PL/SQL Block Section 3.1: An example of an anonymous block DECLARE -- declare a variable message VARCHAR2(20); BEGIN -- assign value to variable message := 'HELLO WORLD'; -- print message to screen DBMS_OUTPUT.PUT_LINE(message); END; /
📄 Page 15
GoalKicker.com – Oracle® Database Notes for Professionals 9 Chapter 4: PL/SQL procedure PL/SQL procedure is a group of SQL statements stored on the server for reuse. It increases the performance because the SQL statements do not have to be recompiled every time it is executed. Stored procedures are useful when same code is required by multiple applications. Having stored procedures eliminates redundancy, and introduces simplicity to the code. When data transfer is required between the client and server, procedures can reduce communication cost in certain situations. Section 4.1: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] TYPE [, ...])] {IS | AS} < declarations > BEGIN < procedure_body > EXCEPTION -- Exception-handling part begins <EXCEPTION handling goes here > WHEN exception1 THEN exception1-handling-statements END procedure_name; procedure-name specifies the name of the procedure. [OR REPLACE] option allows modifying an existing procedure. The optional parameter list contains name, mode and types of the parameters. IN represents that value will be passed from outside and OUT represents that this parameter will be used to return a value outside of the procedure. If no mode is specified, parameter is assumed to be of IN mode. In the declaration section we can declare variables which will be used in the body part. procedure-body contains the executable part. The AS keyword is used instead of the IS keyword for creating a standalone procedure. exception section will handle the exceptions from the procedure. This section is optional. Section 4.2: Hello World The following simple procedure displays the text "Hello World" in a client that supports DBMS_OUTPUT. CREATE OR REPLACE PROCEDURE helloworld AS BEGIN DBMS_OUTPUT.put_line('Hello World!'); END; / You need to execute this at the SQL prompt to create the procedure in the database, or you can run the query below to get the same result: SELECT 'Hello World!' FROM dual; Section 4.3: In/Out Parameters PL/SQL uses IN, OUT, IN OUT keywords to define what can happen to a passed parameter. IN specifies that the parameter is read only and the value cannot be changed by the procedure.
📄 Page 16
GoalKicker.com – Oracle® Database Notes for Professionals 10 OUT specifies the parameter is write only and a procedure can assign a value to it, but not reference the value. IN OUT specifies the parameter is available for reference and modification. PROCEDURE procedureName(x IN INT, strVar IN VARCHAR2, ans OUT VARCHAR2) ... ... END procedureName; procedureName(firstvar, secondvar, thirdvar); The variables passed in the above example need to be typed as they are defined in the procedure parameter section.
📄 Page 17
GoalKicker.com – Oracle® Database Notes for Professionals 11 Chapter 5: Data Dictionary Section 5.1: Describes all objects in the database SELECT * FROM dba_objects Section 5.2: To see all the data dictionary views to which you have access SELECT * FROM dict Section 5.3: Text source of the stored objects USER_SOURCE describes the text source of the stored objects owned by the current user. This view does not display the OWNER column. SELECT * FROM user_source WHERE TYPE='TRIGGER' AND LOWER(text) LIKE '%order%' ALL_SOURCE describes the text source of the stored objects accessible to the current user. SELECT * FROM all_source WHERE owner=:owner DBA_SOURCE describes the text source of all stored objects in the database. SELECT * FROM dba_source Section 5.4: Get list of all tables in Oracle SELECT owner, table_name FROM all_tables ALL_TAB_COLUMNS describes the columns of the tables, views, and clusters accessible to the current user. COLS is a synonym for USER_TAB_COLUMNS. SELECT * FROM all_tab_columns WHERE table_name = :tname Section 5.5: Privilege information All roles granted to user. SELECT * FROM dba_role_privs WHERE grantee= :username Privileges granted to user: system privileges1. SELECT *
📄 Page 18
GoalKicker.com – Oracle® Database Notes for Professionals 12 FROM dba_sys_privs WHERE grantee = :username object grants2. SELECT * FROM dba_tab_privs WHERE grantee = :username Permissions granted to roles. Roles granted to other roles. SELECT * FROM role_role_privs WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username) system privileges1. SELECT * FROM role_sys_privs WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username) object grants2. SELECT * FROM role_tab_privs WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username) Section 5.6: Oracle version SELECT * FROM v$version
📄 Page 19
GoalKicker.com – Oracle® Database Notes for Professionals 13 Chapter 6: Dates Section 6.1: Date Arithmetic - Dierence between Dates in Days, Hours, Minutes and/or Seconds In oracle, the difference (in days and/or fractions thereof) between two DATEs can be found using subtraction: SELECT DATE '2016-03-23' - DATE '2015-12-25' AS difference FROM DUAL; Outputs the number of days between the two dates: DIFFERENCE ---------- 89 And: SELECT TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ) AS difference FROM DUAL Outputs the fraction of days between two dates: DIFFERENCE ---------- 1.0425 The difference in hours, minutes or seconds can be found by multiplying this number by 24, 24*60 or 24*60*60 respectively. The previous example can be changed to get the days, hours, minutes and seconds between two dates using: SELECT TRUNC( difference ) AS days, TRUNC( MOD( difference * 24, 24 ) ) AS hours, TRUNC( MOD( difference * 24*60, 60 ) ) AS minutes, TRUNC( MOD( difference * 24*60*60, 60 ) ) AS seconds FROM ( SELECT TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ) AS difference FROM DUAL ); (Note: TRUNC() is used rather than FLOOR() to correctly handle negative differences.) Outputs: DAYS HOURS MINUTES SECONDS ---- ----- ------- ------- 1 1 1 12
📄 Page 20
GoalKicker.com – Oracle® Database Notes for Professionals 14 The previous example can also be solved by converting the numeric difference to an interval using NUMTODSINTERVAL(): SELECT EXTRACT( DAY FROM difference ) AS days, EXTRACT( HOUR FROM difference ) AS hours, EXTRACT( MINUTE FROM difference ) AS minutes, EXTRACT( SECOND FROM difference ) AS seconds FROM ( SELECT NUMTODSINTERVAL( TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ), 'DAY' ) AS difference FROM DUAL ); Section 6.2: Setting the Default Date Format Model When Oracle implicitly converts from a DATE to a string or vice-versa (or when TO_CHAR() or TO_DATE() are explicitly called without a format model) the NLS_DATE_FORMAT session parameter will be used as the format model in the conversion. If the literal does not match the format model then an exception will be raised. You can review this parameter using: SELECT VALUE FROM NLS_SESSION_PARAMETERS WHERE PARAMETER = 'NLS_DATE_FORMAT'; You can set this value within your current session using: ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'; (Note: this does not change the value for any other users.) If you rely on the NLS_DATE_FORMAT to provide the format mask in TO_DATE() or TO_CHAR() then you should not be surprised when your queries break if this value is ever changed. Section 6.3: Date Arithmetic - Dierence between Dates in Months or Years The difference in months between two dates can be found using the MONTHS_BETWEEN( date1, date2 ): SELECT MONTHS_BETWEEN( DATE '2016-03-10', DATE '2015-03-10' ) AS difference FROM DUAL; Outputs: DIFFERENCE ---------- 12 If the difference includes part months then it will return the fraction of the month based on there being 31 days in each month: SELECT MONTHS_BETWEEN( DATE '2015-02-15', DATE '2015-01-01' ) AS difference FROM DUAL; Outputs:
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List