PLSQL Cont…
Most Common Oracle Data Types
VARCHAR2
Stores variable-length character data.
Takes a required parameter that specifies amaximum length up to 32,767 bytes.
Does not use a constant or a variable tospecify the maximum length; an integer literalmust be used.
The maximum width of a VARCHAR2database column is 4000 bytes
Most Common Oracle Data Types
CHAR
Stores fixed-length (blank-padded if necessary)character data.
Takes an optional parameter that specifies amaximum length up to 32,767
Does not use a constant or variable to specify themaximum length; an integer literal must be used. Ifmaximum length is not specified it defaults to 1.
The maximum width of a CHAR database column is2000 bytes; the default is 1 byte.
Most Common Oracle Data Types
Number
Stores fixed or floating-point numbers of virtually anysize.
Precision is the total number of digits.
Scale determines where rounding occurs.
It is possible to specify precision and omit scale, inwhich case scale is 0 and only integers are allowed.
Constants or variables cannot be used to specifyprecision and scale; integer literals must be used.
Maximum precision of a NUMBER value is 38decimal digits.
Scale can range from -84 to 127
Most Common Oracle Data Types
Binary Integer
Stores signed integer variables
Compares to the NUMBER data type.BINARY_INTEGER variables are stored in thebinary format, which takes less space.
Calculations are faster
Can store any integer value within range.
This data type is used primarily for indexing aPL/SQL table.
Most Common Oracle Data Types
DATE
Stores fixed-length date values.
Valid dates for DATE variables include January 1,4712 B.C. to December 31, A.D. 9999.
When stored in a database column, date valuesinclude the time of day in seconds since midnight.The date portion defaults to the first day of the currentmonth; the time portion defaults to midnight.
Dates are actually stored in binary format and will bedisplayed according to the default format.
Most Common Oracle Data Types
TIMESTAMP
This is a new data type introduced with theOracle 9i. It is an extension of the DATE data-type. It stores fixed-length date values withprecision down to a fraction of a second.
Most Common Oracle Data Types
BOOLEAN
Stores the values TRUE and FALSE and thenon value NULL. Recall that NULL stands formissing, unknown, or inapplicable value.
Only the values TRUE and FALSE and thenon value NULL can be assigned to aBOOLEAN variable.
The values TRUE and FALSE cannot beinserted into a database column.
Most Common Oracle Data Types
Long
Stores variable-length character strings.
The LONG data type is like the VARCHAR2 datatype, except that the maximum length of a LONGvalue is 2 gb.
You cannot select a value longer than 4000 bytesfrom a LONG column into a LONG variable.
LONG columns can store text, arrays of characters, oreven short documents. You can reference LONGcolumns in UPDATE, INSERT, and (most) SELECTstatements, but not in expressions, SQL functioncalls, or certain SQL clauses, such as WHERE,GROUP BY, and CONNECT BY.
Most Common Oracle Data Types
LONG RAW
Stores raw binary data of variable length up to2 gigabytes.
LOB (Large Object)
There are four types of LOBS: BLOB, CLOB,NCLOB, and BFILE. These can store binaryobjects such as image or video files, up to 4gb in length.
BFILE is a large binary file stored outside thedatabase. The maximum size is 4 gigabytes.
Most Common Oracle Data Types
ROWID
Internally, every Oracle database table has a ROWIDpseudocolumn, which stores binary values calledrowids.
Rowids uniquely identify rows and provide the fastestway to access particular rows.
Use thje ROWID data type to store rowids in areadable format.
When you select or fetch a rowid into a ROWIDvariable, you can use the function ROWIDTOCHAR,which converts the binary value into an 18-bytecharacter string and returns it in that format.
Operators (Delimiters): theSeparators in an Expression
Arithmetic(**,*,/,+,-)
Comparison(=,<>,!=,<,>,<=,>=,LIKE, IN,BETWEEN, IS NULL)
Logical (AND, OR, NOT)
String (||,LIKE)
Variables Initialization withSELECT INTO
In PL/SQL, there are two methods of givingvalue to variables in a PL/SQL block.
Initialization with the “:=” syntax.
Initialization with a select statement by use ofSELECT INTO syntax. A variable that has beendeclared in the declaration section of the PL/SQLblock can later be given a value with a SELECTstatement.
It is important to note that any single rowfunction can be performed on the item to givethe variable a calculated value.
Variables Initialization withSELECT INTO
DECLARE
v_average_cost VARCHAR2(10);
BEGIN
SELECT TO_CHAR(AVG(cost), ‘$9,999.99’)
INTO v_average_cost
FROM course;
DBMS_OUTPUT.PUT_LINE(‘The average cost ofa course in the CTA program is’||v_average_cost);
END;
Variables Initialization withSELECT INTO
The TO_CHAR function is used to formatthe cost; in doing this, the number datatype is converted to a character data type.Once the variable has a value; it can bedisplayed to the screen in APEX.
Variables Initialization withSELECT INTO
It is also possible to insert data into adatabase table (friends) in PL/SQL
Variables Initialization withSELECT INTO
DECLARE
V_ID FRIENDS.ID%TYPE;
V_LNAME FRIENDS.LNAME%TYPE;
V_FNAME FRIENDS.FNAME%TYPE;
V_ADDRESS FRIENDS.ADDRESS%TYPE;
BEGIN
SELECT 111, ‘CAPTAIN’, ‘PLANET’, ‘SPARTA’
INTO V_ID, V_LNAME, V_FNAME, V_ADDRESS
FROM DUAL;
INSERT INTO FRIENDS (ID, LNAME, FNAME, ADDRESS)VALUES (V_ID, V_LNAME, V_FNAME, V_ADDRESS);
END;
PL/SQL Programming Exercise
Create a student table with the followingfields: ID, lastname, zip, created_by,created_date, modified_date,registration_date in the Object browser.Then write a PL/SQL block that will inserta new student in the student table. Makesure that you get the highest ID value andthen add 1 to it in order to generate aunique ID number.
PL/SQL Programming Exercise
DECLARE
v_max_id number;
BEGIN
SELECT MAX(student_id)
INTO v_max_id
FROM student;
INSERT into student
(student_id, last_name, zip,
created_by, created_date,
modified_by, modified_date,
registration_date
)
VALUES (v_max_id + 1, ‘Curly’, 11238, ‘Tops’, ’01-JAN-99’, ‘Tops’,’01-JAN-99’,’01-JAN-99’);
END;
Using an Oracle Sequence
An Oracle sequence is an Oracle databaseobject that can be used to generate uniquenumbers. You can use sequences toautomatically generate primary key values.
Once a sequence is created, you can access itsvalues in SQL statements with thesepseudocolumns:
CURRVAL – returns the current value of thesequence
NEXTVAL – increments the sequence andreturns the new value.
Drawing numbers from a sequence
A sequence value can be inserted directlyinto a table without first selecting it.
SEQUENCE EXAMPLE
CREATE TABLE test01(col1 number);
CREATE SEQUENCE test_seq
INCREMENT BY 5;
BEGIN
INSERT INTO test01
VALUES(test_seq.NEXTVAL);
END;
SELECT * FROM test01
The IF Statement
An IF-THEN statement specifies thesequence of statements to execute only ifthe condition evaluates to TRUE. Whenthis condition evaluates to FALSE, there isno special action to take except to proceedwith the execution of the program.
Example of IF-THEN statement
DECLARE
v_num1 NUMBER := 5;
v_num2 NUMBER := 3;
v_temp NUMBER;
BEGIN
IF v_num1 > v_num2 THEN
v_temp := v_num1;
v_num1 := v_num2;
v_num2 := v_temp;
END IF;
DBMS_OUTPUT.PUT_LINE(‘v_num1 = ’|| v_num1);
DBMS_OUTPUT.PUT_LINE(‘v_num2 = ’|| v_num2);
END;
IF-THEN-ELSE
The IF-THEN-ELSE construct should beused when trying to choose between twomutually exclusive actions.
IF-THEN-ELSE Example
DECLARE
v_num1 NUMBER := 0;
v_num2 NUMBER;
BEGIN
IF v_num1 = v_num2 THEN
DBMS_OUTPUT.PUT_LINE (‘v_num1 = v_num2’);
ELSE
DBMS_OUTPUT.PUT_LINE (‘v_num1 != v_num2’);
END IF;
END;
LOOPS
The EXIT WHEN statement causes a loop toterminate only if the EXIT WHEN conditionevaluates to TRUE. Control is then passedto the first executable statement after theEND LOOP statement.
LOOP Example
DECLARE
v_counter BINARY_INTEGER := 0;
BEGIN
LOOP
v_counter := v_counter + 1;
DBMS_OUTPUT.PUT_LINE('v_counter=' ||v_counter);
IF v_counter = 5 THEN
EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Done…');
END;
Cursors
A cursor is a handle, or a pointer to anarea of memory that contains informationabout an SQL statement that is beingprocessed such as rows returned by aSELECT statement one row at a time.
A cursor is named so that it can bereferenced.
2 types of cursors
1.Implicit cursor – automatically declared byOracle every time an SQL statement isexecuted. The user will not be aware of thishappening and will not be able to control orprocess the information in an implicit cursor.
2.Explicit cursor – defined by the program forany query that returns more than one row ofdata. That means the programmer hasdeclared the cursor within the PL/SQL codeblock. This declaration allows for theapplication to sequentially process each row ofdata as it is returned by the cursor.
Processing an Implicit Cursor
Any given PL/SQL block issues an implicit cursorwhenever an SQL statement is executed, as long as anexplicit cursor does not exist for that SQL statement
A cursor is automatically associated with every DML(data manipulation language) statement
All update and delete statements have cursors that identify theset of rows that will be affected by the operation. An implicitcursor cannot tell you how many rows were affected by anupdate. SQL%ROWCOUNT returns numbers of rows updated.
An insert statement needs a place to receive the data that is tobe inserted in the database; the implicit cursor fulfills this need.
Processing an Implicit Cursor
During the processing of an implicit cursor,Oracle automatically performs the OPEN,FETCH and CLOSE operations.
The most recently opened cursor is called theSQL% cursor.
Oracle automatically associates an implicitcursor with the SELECT INTO statement andfetches the values for the variables,v_first_name and v_last_name. Once theSELECT INTO statement completes, Oraclecloses the implicit cursor.
Creating a Table for Exercises
CREATE TABLE employee(
id varchar2(20),
lname varchar2(50),
fname varchar2(50)
);
INSERT INTO employee(id, lname, fname) VALUES(‘01’,’Asterix’,’Gaul’);
INSERT INTO employee(id, lname, fname) VALUES(‘02’,’Obelix’,’Gaul’);
INSERT INTO employee(id, lname, fname) VALUES(‘123’,’Rodimus’,’Autobot’);
Cursor Example
BEGIN
UPDATE EMPLOYEE
SET FNAME = ‘B’
WHERE LNAME LIKE ‘R%’;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;
Cursor Example
DECLARE
v_first_name VARCHAR2(35);
v_last_name VARCHAR2(35);
BEGIN
SELECT FNAME, LNAME
INTO v_first_name, v_last_name
FROM EMPLOYEE
WHERE ID = 123;
DBMS_OUTPUT.PUT_LINE ('EMPLOYEE NAME: ' || v_first_name || ' ' ||v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
('There is no employee with EMPLOYEE ID 123');
END;
Explicit Cursor
Must be named in the declare section ofthe PL/SQL block.
Gives more programmatic control to theprogrammer
Oracle interactive series advices us toname a cursor as c_cursorname. By usinga c_ in the beginning of the name, it willalways clear to you that the name isreferencing a cursor.
Explicit Cursor
When using an explicit cursor, we must dothe following.
Declare
Open
Fetch
Close
Explicit Cursor Example
DECLARE
v_eid EMPLOYEE.ID%TYPE;
CURSOR c_employee IS
SELECT ID
FROM EMPLOYEE
WHERE ID < 110;
BEGIN
OPEN c_employee;
LOOP
FETCH c_employee INTO v_eid;
IF c_employee%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Just fetched row' || TO_CHAR(c_employee%ROWCOUNT)||'EMPLOYEE ID:'|| v_eid);
ELSE
EXIT;
END IF;
END LOOP;
CLOSE c_employee;
END;
Explicit Cursor
In the declaration section, we defined cursornamed c_employee, based on theEMPLOYEE table such that the ID < 110.This returns the field ID based on thecursor.
To open the cursor, we just say
open c_employee
Explicit Cursor
To fetch the contents of the cursor, wedeclare a FETCH. The FETCH commandis used to retrieve one row at a time fromthe active set. This is generally doneinside a loop. The values of each row inthe active set can then be stored into thecorresponding variables or PL/SQL recordone at a time, performing operations oneach on successively.
Explicit Cursor
After each FETCH, the active set pointer ismoved forward to the next row. Thus, eachfetch will return successive rows of theactive set, until the entire set is returned.The last FETCH will not assign values tothe output variables; they will still containtheir prior values.
Explicit Cursor Attributes
Explicit Cursor Attributes
Cursor Attribute
Syntax
Explanation
%NOTFOUND
Cursor_name%NOTFOUND
A boolean attribute that returns TRUEif the previous FETCH did not return arow, and FALSE if it did.
%FOUND
Cursor_name%found
A boolean attribute that returns TRUEif the previous FETCH returned a row,and FALSE if it did not.
%ROWCOUNT
Cursor_name%ROWCOUNT
# of records fetched from a cursor atthat point in time
%ISOPEN
Cursor_name%ISOPEN
A boolean attribute that returns TRUEif cursor is open, FALSE if it is not.
A cursor that returns the first fiveemployee names from theemployee table
DECLARE
CURSOR c_employee_name IS
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE rownum <= 5;
vr_employee_name c_employee_name%ROWTYPE;
BEGIN
OPEN c_employee_name;
LOOP
FETCH c_employee_name INTO vr_employee_name;
EXIT WHEN c_employee_name%NOTFOUND;
END LOOP;
        CLOSE c_employee_name;
        DBMS_OUTPUT.PUT_LINE('Employee name: ' || vr_employee_name.FNAME ||vr_employee_name.LNAME);
END;
Using cursor for Loops and NestingCursors
An alternative method of handling cursors
Here, the process of opening, fetching,and closing is handled implicitly
Makes the blocks much simpler to codeand easier to maintain
Opening fetching and closing is handledimplicitly
Makes the blocks much simpler to codeand easier to maintain
Make a table to illustrate theexamples
Create table table_log(descriptionVARCHAR2 (250));
PROCEDURES
A procedure is a module performing one or moreactions; it does not need to return any value.
A procedure may have 0 to many parameters.
Every procedure has two parts:
The header portion, which comes before AS(sometimes you will see IS – they areinterchangeable), keyword and the body whichis everything after the IS keyword.
PROCEDURES
The word REPLACE s optional. When theword replace is not used in the header ofthe procedure, in order to change the codein the procedure, the procedure must bedropped and then re-created. Since it isvery common to change the code of theprocedure, especially when it is underdevelopment, it is strongly recommendedto use the OR REPLACE option
Procedure Syntax
CREATE OR REPLACE PROCEDUREname
AS
[local declarations]
BEGIN
executable statements
[Exception handlers]
END [name];
FUNCTIONS
Functions are another type of stored code andare very similar to procedures.
The significant difference is that a function is aPL/SQL block that returns a single value.
Functions can accept one many, or noparameters, but a function must have a returnclause in the executable section of the function.
A function is not a stand-alone executable in theway that a procedure is: It must be used in somecontext. You can think of it as a sentencefragment.
FUNCTIONS
A function has output that needs to beassigned to a variable or it can be used ina SELECT statement.
The function must have a RETURN valuedeclared in the header, and it must returnvalues for all varying possible executionstreams.
There may be more than one RETURNstatement.
Function Example
CREATE OR REPLACE FUNCTION show_address(i_ID EMPLOYEE.ID%TYPE)
RETURN varchar2
AS v_address varchar2(50);
BEGIN
SELECT ADDRESS
INTO v_address
FROM EMPLOYEE
WHERE ID = i_ID;
RETURN v_address;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
RETURN('The employee is not in the database');
WHEN OTHERS
THEN
RETURN ('Error in running show_address');
END;