PL/SQL Notes
PL/SQL Notes
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's proprietary procedural extension to the SQL database language, used in the Oracle database. Some other SQL database management systems offer similar extensions to the SQL language. PL/SQL's syntax strongly resembles that of Ada, and just like Ada compilers of the 1980s the PL/SQL runtime system uses Diana as intermediate representation.The key strength of PL/SQL is its tight integration with the Oracle database.PL/SQL is one of three languages embedded in the Oracle Database, the other two being SQL and Java.
History
PL/SQL made its first appearance in Oracle Forms v3. A few years later, it was included in the Oracle Database server v7 (as database procedures, functions, packages, triggers and anonymous blocks) followed by Oracle Reports v2.
Functionality
PL/SQL supports the following: variables, conditions, arrays, and exceptions. Implementations from version 8 of Oracle Database onwards have included features associated with object-orientation. The underlying SQL functions as a declarative language. Standard SQLunlike some functional programming languagesdoes not require implementations to convert tail calls to jumps. The open standard SQL does not readily provide "first row" and "rest of table" accessors, and it cannot easily perform some constructs such as loops. PL/SQL, however, as a Turing-complete procedural language that fills in these gaps, allows Oracle database developers to interface with the underlying relational database in an imperative manner. SQL statements can make explicit in-line calls to PL/SQL functions, or can cause PL/SQL triggers to fire upon pre-defined Data Manipulation Language (DML) events. PL/SQL stored procedures (functions, procedures, packages, and triggers) performing DML get compiled into an Oracle database: to this extent their SQL code can undergo syntax-checking. Programmers working in an Oracle database environment can construct PL/SQL blocks of functionality to serve as procedures, functions; or they can write in-line segments of PL/SQL within SQL*Plus scripts. While programmers can readily incorporate SQL DML statements into PL/SQL (as cursor definitions, for example, or using the SELECT ... INTO syntax), Data Definition Language (DDL) statements such as CREATE TABLE/DROP INDEX etc require the use of "Dynamic SQL". Earlier versions of Oracle Database required the use of a complex built-in DBMS_SQL package for Dynamic SQL where the system needed to explicitly parse and execute an SQL statement. Later versions have included an EXECUTE IMMEDIATE syntax
called "Native Dynamic SQL" which considerably simplifies matters. Any use of DDL in an Oracle database will result in an implicit commit. Programmers can also use Dynamic SQL to execute DML where they do not know the exact content of the statement in advance. PL/SQL offers several pre-defined packages for specific purposes. Such PL/SQL packages include:
DBMS_OUTPUT - for output operations to non-database destinations DBMS_JOB - for running specific procedures/functions at a particular time (i.e. scheduling) DBMS_XPLAN - for formatting "Explain Plan" output DBMS_SESSION - provides access to SQL ALTER SESSION and SET ROLE statements, and other session information. DBMS_METADATA - for extracting meta data from the data dictionary (such as DDL statements) UTL_FILE - for reading and writing files on disk UTL_HTTP - for making requests to web servers from the database UTL_SMTP - for sending mail from the database (via an SMTP server)
Oracle Corporation customarily adds more packages and/or extends package functionality with each successive release of Oracle Database.
Note that blocks can be nested within blocks. The DECLARE section specifies the datatypes of variables, constants, collections, and userdefined types. The block between BEGIN and END specifies executable procedural code. Exceptions, errors which arise during the execution of the code, have one of two types:
1. pre-defined exceptions 2. user-defined exceptions. Programmers have to raise user-defined exceptions explicitly. They can do this by using the RAISE command, with the syntax:
RAISE <exception name>
Oracle
Corporation has pre-defined several exceptions like NO_DATA_FOUND, TOO_MANY_ROWS, etc. Each exception has a SQL Error Number and SQL Error Message associated with it. Programmers can access these by using the SQLCODE and SQLERRM functions. The DECLARE section defines and (optionally) initialises variables. If not initialised specifically they default to NULL. For example:
DECLARE number1 NUMBER(2); number2 NUMBER(2) := 17; text1 VARCHAR2(12) := 'Hello world'; text2 DATE := SYSDATE; BEGIN SELECT street_number INTO number1 FROM address WHERE name = 'Smith'; END;
The symbol := functions as an assignment operator to store a value in a variable. The major datatypes in PL/SQL include NUMBER, INTEGER, CHAR, VARCHAR2, DATE, TIMESTAMP, TEXT etc.
Functions
Functions in PL/SQL are a collection of SQL and PL/SQL statements that perform a task and should return a value to the calling environment.
CREATE OR REPLACE FUNCTION <function_name> IS/AS {Variable declaration} {CONSTANT declaration} RETURN return_type BEGIN Pl/SQL Block; EXCEPTION EXCEPTION Block; END;
Numeric variables
variable_name number(P[,S]) := value; To define a numeric variable, the programmer appends the variable type NUMBER to the name definition. To specify the (optional) precision(P) and the (optional) scale (S), one can further append these in round brackets, separated by a comma. ("Precision" in this context refers to the number of digits which the variable can hold, "scale" refers to the number of digits which can follow the decimal point.) A selection of other datatypes for numeric variables would include: binary_float, binary_double, dec, decimal, double precision, float, integer, int, numeric, real, smallint, binary_integer
Character variables
variable_name varchar2(L) := 'Text'; To define a character variable, the programmer normally appends the variable type VARCHAR2 to the name definition. There follows in brackets the maximum number of characters which the variable can store. Other datatypes for character variables include: varchar, char, long, raw, long raw, nchar, nchar2, clob, blob, bfile
Date variables
variable_name date := '01-Jan-2005'; Oracle provides a number of data types that can store dates (DATE, DATETIME, TIMESTAMP etc), however DATE is most commonly used. Programmers define date variables by appending the datatype code "DATE" to a variable name. The TO_DATE function can be used to convert strings to date values. The function converts the first quoted string into a date, using as a definition the second quoted string, for example:
TO_DATE('31-12-2004','dd-mm-yyyy')
"or"
TO_DATE ('31-Dec-2004','dd-mon-yyyy', 'NLS_DATE_LANGUAGE = American')
To convert the dates to strings one uses the function TO_CHAR (date_string, format_string).
For example:
DECLARE TYPE t_address IS RECORD ( name address.name%TYPE, street address.street%TYPE, street_number address.street_number%TYPE, postcode address.postcode%TYPE); v_address t_address; BEGIN SELECT name, street, street_number, postcode INTO v_address FROM address WHERE ROWNUM = 1; END;
This sample program defines its own datatype, called t_address, which contains the fields name, street, street_number and postcode. so according the example we are able to copy the data from database to the fields in program. Using this datatype the programmer has defined a variable called v_address and loaded it with data from the ADDRESS table. Programmers can address individual attributes in such a structure by means of the dotnotation, thus: "v_address.street := 'High Street';"
Conditional Statements
The following code segment shows the IF-THEN-ELSIF construct. The ELSIF and ELSE parts are optional so it is possible to create simpler IF-THEN or, IF-THEN-ELSE constructs.
IF x = 1 THEN sequence_of_statements_1; ELSIF x = 2 THEN sequence_of_statements_2; ELSIF x = 3 THEN sequence_of_statements_3; ELSIF x = 4 THEN sequence_of_statements_4; ELSIF x = 5 THEN sequence_of_statements_5; ELSE sequence_of_statements_N; END IF;
Array handling
PL/SQL refers to arrays as "collections". The language offers three types of collections: 1. Index-by tables (associative arrays) 2. Nested tables 3. Varrays (variable-size arrays) Programmers must specify an upper limit for varrays, but need not for index-by tables or for nested tables. The language includes several collection methods used to manipulate collection elements: for example FIRST, LAST, NEXT, PRIOR, EXTEND, TRIM, DELETE, etc. Index-by tables can be used to simulate associative arrays, as in this example of a memo function for Ackermann's function in PL/SQL.
Looping
As a procedural language by definition, PL/SQL provides several iteration constructs, including basic LOOP statements, WHILE loops, FOR loops, and Cursor FOR loops.
LOOP statements
Syntax:
LOOP statement1; statement2; END LOOP;
WHILE loops
Syntax:
WHILE LOOP ...do something... END LOOP;
Cursor-for loops automatically open a cursor, read in their data and close the cursor again As an alternative, the PL/SQL programmer can pre-define the cursor's SELECT-statement in advance in order (for example) to allow re-use or to make the code more understandable (especially useful in the case of long or complex queries).
DECLARE CURSOR cursor_person IS SELECT person_code FROM people_table; BEGIN FOR RecordIndex IN cursor_person LOOP DBMS_OUTPUT.PUT_LINE(RecordIndex.person_code); END LOOP; END; Example DECLARE
var NUMBER; /* this "var" is not in the same scope as the for loop "var" a reference to "var" after the "end loop;" would find its
BEGIN value to be null */ /*N.B. for loop variables in pl/sql are new declarations, with scope only inside the loop */ FOR var IN 0 ..10 LOOP DBMS_OUTPUT.put_line(var); END LOOP; END;
Output:
0 1 2 3 4 5 6 7 8 9 10
Numeric Datatypes
Data Type Syntax Oracle 9i Oracle 10g Precision can range from 1 to 38. Scale can range from -84 to 127. Precision can range from 1 to 38. Oracle 11g Precision can range from 1 to 38. Scale can range from -84 to 127. Precision can range from 1 to 38. Explanation (if applicable) Where p is the precision and s is the scale. For example, number(7,2) is a number that has 5 digits before the decimal and 2 digits after the decimal. Where p is the precision and s is the scale. For example, numeric(7,2) is a number that has 5 digits before the decimal and 2 digits after the decimal. float dec(p,s) Precision can range from 1 to 38. Precision can range from 1 to 38. Precision can range from 1 to 38. Where p is the precision and s is the scale. For example, dec(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal. decimal(p,s) Precision can range from 1 to 38. Precision can range from 1 to 38. Precision can range from 1 to 38. Where p is the precision and s is the scale. For example, decimal(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal.
number(p,s) Precision can range from 1 to 38. Scale can range from -84 to 127. numeric(p,s) Precision can range from 1 to 38.
Character Datatypes
Data Type Syntax char(size) Oracle 9i Maximum size of 2000 bytes. Maximum size of 2000 bytes. Oracle 10g Maximum size of 2000 bytes. Maximum size of 2000 bytes. Maximum size of 4000 bytes. Maximum size of 4000 bytes. Oracle 11g Maximum size of 2000 bytes. Maximum size of 2000 bytes. Maximum size of 4000 bytes. Maximum size of 4000 bytes. Explanation (if applicable) Where size is the number of characters to store. Fixed-length strings. Space padded. Where size is the number of characters to store. Fixed-length NLS string Space padded. Where size is the number of characters to store. Variable-length NLS string. Where size is the number of characters to store. Variable-length string.
nchar(size)
nvarchar2(size) Maximum size of 4000 bytes. varchar2(size) Maximum size of 4000 bytes.
1. The declaration section defines all variables, cursors, subprograms, and other elements to be used in the code. 2. The declaration section is optional. 3. The procedural section contains the main body of the routine. 4. The procedural section starts with the begin keyword and ends with the exception keyword or the end keyword if you have no exception section. 5. The procedural section is the only mandatory part of the code. 6. You must have at least one line of executable code in the procedural section. 7. You can use the NULL command to indicate that nothing should be executed. 8. The exception section is also optional. 9. The exception section allows the program to intercept and process exceptions.
Cursors
You use a cursor when you have a SELECT statement that returns more than one row from the database. A cursor is basically a set of rows that you can access one at a time. You retrieve the rows into the cursor using your SELECT statement and then fetch the rows from the cursor. You may follow five steps when using a cursor: 1. Declare variables to store the column values from the SELECT statement. 2. Declare the cursor, specifying your SELECT statement. 3. Open the cursor. 4. Fetch the rows from the cursor. 5. Close the cursor. The syntax for declaring a cursor is as follows:
CURSOR cursor_name IS SELECT_statement; where cursor_name specifies the name of the cursor.
SELECT_statement is a SELECT statement. You open a cursor using the OPEN statement, which must be placed in the executable section of the block. To read each row from the cursor, you can use the FETCH statement. The FETCH statement reads the column values into the variables that you specify;
FETCH uses the following syntax: FETCH cursor_name INTO variable[, variable ...];
Where 1. cursor_name specifies the name of the cursor. 2. variable is a previously declared variable into which values from the cursor's SELECT statement are stored. Once you've finished with the cursor, the final step is to close the cursor using the CLOSE statement. Closing your cursors frees up system resources
Functions
A function is similar to a procedure except that a function must return a value. You create a function using the CREATE FUNCTION statement. The simplified syntax for the CREATE FUNCTION statement is as follows:
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] RETURN type {IS | AS} BEGIN function_body END function_name;
Where 1. OR REPLACE specifies the function that is to replace an existing function if present. 2. type specifies the PL/SQL type of the parameter. 3. The body of a function must return a value of the PL/SQL type specified in the RETURN clause.
Triggers
A trigger is a procedure that is run automatically by the database when a specified SQL DML INSERT, UPDATE, or DELETE statement is run against a table. Triggers are useful for doing things like advanced auditing of changes made to column values in a table. When a Trigger Runs 1. A trigger can fire before or after the SQL statement runs. 2. A trigger can may be run once for every row affected. Such a trigger is known as a row-level trigger. 3. A trigger can may be run for all the rows. Such trigger is known as a statement-level trigger. 4. A row-level trigger has access to the old and new column values when the trigger fires as a result of an UPDATE statement on that column. 5. The firing of a trigger may also be limited using a trigger condition. Different events may fire a trigger, but these events are always divided into three groups: 1. DML triggers, 2. INSTEAD OF triggers, and 3. system event triggers. DML triggers are the triggers on INSERT/UPDATE/DELETE operations in any table.
Creating a User
To create a user in the database, you use the CREATE USER statement. The simplified syntax for the CREATE USER statement is as follows:
CREATE USER user_name IDENTIFIED BY password [DEFAULT TABLESPACE default_tablespace] [TEMPORARY TABLESPACE temp_tablespace];
Where 1. If you omit a default tablespace, the default SYSTEM tablespace is used. 2. Tablespaces are used by the database to separate objects. 3. temp_tablespace specifies the default tablespace where temporary objects are stored. 4. If you omit a temporary tablespace, the default SYSTEM tablespace is used.
1.
What is a transaction ? Answer: A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.
2.
What is implicit cursor and how is it used by Oracle ? Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created by Oracle for each individual SQL.
3.
What is PL/SQL? Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools.
4.
Is there a limit on the size of a PL/SQL block? Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K.You can run the following select statement to query the size of an existing package or procedure. SQL> select * from dba_object_size where name = 'procedure_name'
5.
How can I protect my PL/SQL source code? Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code.This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original).This way you can distribute software without having to worry about exposing your proprietary algorithms and methods.SQL*Plus and SQL*DBA will still understand and know how to execute such scripts.Just be careful, there is no "decode" command available. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy
6.
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ? Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END;