PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
Chapter 10.
Chapter 4B: More Advanced PL/SQL Programming
VBA Modules, Functions, Variables, and Constants
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to PL/SQL
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
SQL Within PL / SQL Chapter 4. 2 SQL Within PL / SQL SQL Statements DML in PL / SQL Pseudocolums Transaction Control.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Cursor and Exception Handling By Nidhi Bhatnagar.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
Other database objects (Sequence). What Is a Sequence? A sequence: Automatically generates sequential numbers Is a sharable object Is typically used to.
Chapter 6 Additional Database Objects Oracle 10g: SQL.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Sizing Basics  Why Size?  When to size  Sizing issues:  Bits and Bytes  Blocks (aka pages) of Data  Different Data types  Row Size  Table Sizing.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
1 Creating and Modifying Database Objects. 2 An Oracle database consists of multiple user accounts Each user account owns database objects Tables Views.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Application Development using PL/SQL Programming.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Using SQL in PL/SQL ITEC 224 Database Programming.
Data types  CHAR (size): This data type is used to store character strings values of fixed length. The size in brackets determines the number of characters.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Sql DDL queries CS 260 Database Systems.
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
implicit and an explicit cursor
Academic Year 2015 Autumn. MODULE CC2006NI: Data Modelling and Database Systems Academic Year 2015 Autumn.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
Declaring PL/SQL Variables
PL/SQL INTRODUCTION.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ITEC 224 Database Programming
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
PL/pgSQL
Interacting with the Oracle Server
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Database Management Systems 2
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Presentation transcript:

PLSQL Cont…

Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length up to 32,767 bytes. –Does not use a constant or a variable to specify the maximum length; an integer literal must be used. –The maximum width of a VARCHAR2 database 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 a maximum length up to 32,767 –Does not use a constant or variable to specify the maximum length; an integer literal must be used. If maximum length is not specified it defaults to 1. –The maximum width of a CHAR database column is 2000 bytes; the default is 1 byte.

Most Common Oracle Data Types Number –Stores fixed or floating-point numbers of virtually any size. –Precision is the total number of digits. –Scale determines where rounding occurs. –It is possible to specify precision and omit scale, in which case scale is 0 and only integers are allowed. –Constants or variables cannot be used to specify precision and scale; integer literals must be used. –Maximum precision of a NUMBER value is 38 decimal 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 the binary format, which takes less space. –Calculations are faster –Can store any integer value within range. –This data type is used primarily for indexing a PL/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 –When stored in a database column, date values include the time of day in seconds since midnight. The date portion defaults to the first day of the current month; the time portion defaults to midnight. –Dates are actually stored in binary format and will be displayed according to the default format.

Most Common Oracle Data Types TIMESTAMP –This is a new data type introduced with the Oracle 9i. It is an extension of the DATE data- type. It stores fixed-length date values with precision down to a fraction of a second.

Most Common Oracle Data Types BOOLEAN –Stores the values TRUE and FALSE and the non value NULL. Recall that NULL stands for missing, unknown, or inapplicable value. –Only the values TRUE and FALSE and the non value NULL can be assigned to a BOOLEAN variable. –The values TRUE and FALSE cannot be inserted into a database column.

Most Common Oracle Data Types Long –Stores variable-length character strings. –The LONG data type is like the VARCHAR2 data type, except that the maximum length of a LONG value is 2 gb. –You cannot select a value longer than 4000 bytes from a LONG column into a LONG variable. –LONG columns can store text, arrays of characters, or even short documents. You can reference LONG columns in UPDATE, INSERT, and (most) SELECT statements, but not in expressions, SQL function calls, 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 to 2 gigabytes. LOB (Large Object) –There are four types of LOBS: BLOB, CLOB, NCLOB, and BFILE. These can store binary objects such as image or video files, up to 4 gb in length. –BFILE is a large binary file stored outside the database. The maximum size is 4 gigabytes.

Most Common Oracle Data Types ROWID –Internally, every Oracle database table has a ROWID pseudocolumn, which stores binary values called rowids. –Rowids uniquely identify rows and provide the fastest way to access particular rows. –Use thje ROWID data type to store rowids in a readable format. –When you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value into an 18-byte character string and returns it in that format.

Operators (Delimiters): the Separators in an Expression Arithmetic(**,*,/,+,-) Comparison(=,<>,!=,, =,LIKE, IN, BETWEEN, IS NULL) Logical (AND, OR, NOT) String (||,LIKE)

Variables Initialization with SELECT INTO In PL/SQL, there are two methods of giving value to variables in a PL/SQL block. –Initialization with the “:=” syntax. –Initialization with a select statement by use of SELECT INTO syntax. A variable that has been declared in the declaration section of the PL/SQL block can later be given a value with a SELECT statement. It is important to note that any single row function can be performed on the item to give the variable a calculated value.

Variables Initialization with SELECT 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 of a course in the CTA program is’|| v_average_cost); END;

Variables Initialization with SELECT INTO The TO_CHAR function is used to format the cost; in doing this, the number data type is converted to a character data type. Once the variable has a value; it can be displayed to the screen in APEX.

Variables Initialization with SELECT INTO It is also possible to insert data into a database table (friends) in PL/SQL

Variables Initialization with SELECT 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 following fields: ID, lastname, zip, created_by, created_date, modified_date, registration_date in the Object browser. Then write a PL/SQL block that will insert a new student in the student table. Make sure that you get the highest ID value and then add 1 to it in order to generate a unique 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 database object that can be used to generate unique numbers. You can use sequences to automatically generate primary key values. Once a sequence is created, you can access its values in SQL statements with these pseudocolumns: CURRVAL – returns the current value of the sequence NEXTVAL – increments the sequence and returns the new value.

Drawing numbers from a sequence A sequence value can be inserted directly into 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 the sequence of statements to execute only if the condition evaluates to TRUE. When this condition evaluates to FALSE, there is no special action to take except to proceed with 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 be used when trying to choose between two mutually 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 to terminate only if the EXIT WHEN condition evaluates to TRUE. Control is then passed to the first executable statement after the END 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 an area of memory that contains information about an SQL statement that is being processed such as rows returned by a SELECT statement one row at a time. A cursor is named so that it can be referenced.

2 types of cursors 1.Implicit cursor – automatically declared by Oracle every time an SQL statement is executed. The user will not be aware of this happening and will not be able to control or process the information in an implicit cursor. 2.Explicit cursor – defined by the program for any query that returns more than one row of data. That means the programmer has declared the cursor within the PL/SQL code block. This declaration allows for the application to sequentially process each row of data as it is returned by the cursor.

Processing an Implicit Cursor Any given PL/SQL block issues an implicit cursor whenever an SQL statement is executed, as long as an explicit 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 the set of rows that will be affected by the operation. An implicit cursor cannot tell you how many rows were affected by an update. SQL%ROWCOUNT returns numbers of rows updated. –An insert statement needs a place to receive the data that is to be 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 the SQL% cursor. Oracle automatically associates an implicit cursor with the SELECT INTO statement and fetches the values for the variables, v_first_name and v_last_name. Once the SELECT INTO statement completes, Oracle closes 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%ROW COUNT); 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 of the PL/SQL block. Gives more programmatic control to the programmer Oracle interactive series advices us to name a cursor as c_cursorname. By using a c_ in the beginning of the name, it will always clear to you that the name is referencing a cursor.

Explicit Cursor When using an explicit cursor, we must do the 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 cursor named c_employee, based on the EMPLOYEE table such that the ID < 110. This returns the field ID based on the cursor. To open the cursor, we just say open c_employee

Explicit Cursor To fetch the contents of the cursor, we declare a FETCH. The FETCH command is used to retrieve one row at a time from the active set. This is generally done inside a loop. The values of each row in the active set can then be stored into the corresponding variables or PL/SQL record one at a time, performing operations on each on successively.

Explicit Cursor After each FETCH, the active set pointer is moved forward to the next row. Thus, each fetch will return successive rows of the active set, until the entire set is returned. The last FETCH will not assign values to the output variables; they will still contain their prior values.

Explicit Cursor Attributes Cursor AttributeSyntaxExplanation %NOTFOUNDCursor_name%NOTFOUNDA boolean attribute that returns TRUE if the previous FETCH did not return a row, and FALSE if it did. %FOUNDCursor_name%foundA boolean attribute that returns TRUE if the previous FETCH returned a row, and FALSE if it did not. %ROWCOUNTCursor_name%ROWCOUNT# of records fetched from a cursor at that point in time %ISOPENCursor_name%ISOPENA boolean attribute that returns TRUE if cursor is open, FALSE if it is not.

A cursor that returns the first five employee names from the employee 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 Nesting Cursors An alternative method of handling cursors Here, the process of opening, fetching, and closing is handled implicitly Makes the blocks much simpler to code and easier to maintain Opening fetching and closing is handled implicitly Makes the blocks much simpler to code and easier to maintain

Make a table to illustrate the examples Create table table_log(description VARCHAR2 (250));

PROCEDURES A procedure is a module performing one or more actions; 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 are interchangeable), keyword and the body which is everything after the IS keyword.

PROCEDURES The word REPLACE s optional. When the word replace is not used in the header of the procedure, in order to change the code in the procedure, the procedure must be dropped and then re-created. Since it is very common to change the code of the procedure, especially when it is under development, it is strongly recommended to use the OR REPLACE option

Procedure Syntax CREATE OR REPLACE PROCEDURE name AS [local declarations] BEGIN executable statements [Exception handlers] END [name];

FUNCTIONS Functions are another type of stored code and are very similar to procedures. The significant difference is that a function is a PL/SQL block that returns a single value. Functions can accept one many, or no parameters, but a function must have a return clause in the executable section of the function. A function is not a stand-alone executable in the way that a procedure is: It must be used in some context. You can think of it as a sentence fragment.

FUNCTIONS A function has output that needs to be assigned to a variable or it can be used in a SELECT statement. The function must have a RETURN value declared in the header, and it must return values for all varying possible execution streams. There may be more than one RETURN statement.

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;