Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
PL/SQL
What is PL/SQL?
• PL/SQL is a block-structured language.
• A block lets you group logically related
declarations and statements.
What is PL/SQL?
• A PL/SQL block has three parts:
– Optional DECLARATIVE part,
– an executable part, and
– Optional EXCEPTION-HANDLING part.
[Block header]
[DECLARE <constants> <variables> <cursors>]
[BEGIN]
<PL/SQL statements>
[EXCEPTION exception handling routine>]
END;
Types of Block
• Anonymous Block
– Are blocks without header
• Named Block
– Blocks having headers
– Can be either Subprogram or triggers
– Can be compiled separately and stored
permanently in an Oracle database, Ready to be
executed
Variables and Constant
• Must declare a constant or
variable before referencing it in other
statements in a declarative part of the block
• Declaring Variable
variablename datatype[(size)] [:= initial value]
Variables and Constant
• Variable Declaration
– Bound Declaration
• Specify size for a variable
• Example: age NUMBER(2); --store 2 digits
– Unbound Declaration
• Allocate maximum memory allowed for that particular
type
• Example: age NUMBER;
Variables and Constant
• Variable Declaration
– Anchored Declaration
• Variable is declared with another variable or a
table column
• %TYPE is used for anchor declaration.
variablename object%TYPE[:= initial value]
• Example: num1 NUMBER[5];
num2 num%TYPE;
empsal EMPLOYEE.SALARY%TYPE;
Variable and Constant
• Assigning Values to a Variable
– Assignment operator := is used to assign value to a
variable.
variablename:=<value/expression>
• Commenting Your Code
– Single Line Comment: starts with double ‘-’
– Multiple Line Comment: /*...*/
Variables and Constants
• Literal
– It is a simply a value, which is not represented by an
identifier
• Constant
– Named literal is called constant
– Declaring Constant
constant_name CONSTANT datatype[(size)] := initial value]
Example: pi CONSTANT NUMBER:=3.14;
PL/SQL DATATYPES
PL/SQL Datatypes
• Datatype identify type of data and associated
operation for handling it.
• PL/SQL provides
– Scalar types
– Composite types
– Reference types
– LOB types
1.Scalar Types
• It is atomic.
– Not made up of other dataypes.
• It holds a single value, such as a number or
character string.
• Falls into four types
– PL/SQL Number Types
– PL/SQL Character and String Types
– PL/SQL Boolean Types
– PL/SQL Date, Time, and Interval Types
1.Scalar Types
• PL/SQL Number Types
– BINARY_DOUBLE, BINARY_FLOAT, BINARY_INTEGER,
DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INT,
INTEGER, NATURAL, NATURALN, NUMBER, NUMERIC,
PLS_INTEGER, POSITIVE, POSITIVEN, REAL, SIGNTYPE,
SMALLINT
• PL/SQL Character and String Types
– CHAR, CHARACTER, LONG, LONG RAW, NCHAR,
NVARCHAR2, RAW, ROWID, STRING, UROWID,
VARCHAR, VARCHAR2
1.Scalar Types
• PL/SQL Boolean Types
– BOOLEAN
• PL/SQL Date, Time, and Interval Types
– DATE, TIMESTAMP, TIMESTAMP WITH TIMEZONE,
TIMESTAMP WITH LOCAL TIMEZONE, INTERVAL
YEAR TO MONTH, INTERVAL DAY TOSECOND
2. Composite Type
• Made up with other datatypes such as the
elements of an ARRAY, RECORD, or TABLE.
3. Reference Datatypes
• A reference type holds values, called pointers,
that designate other program items.
• Include REF CURSORS and REFs to object
types.
4. LOB Types
• A LOB type holds values, that specify the
location of large objects, such as text blocks or
graphic images, that are stored separately
from other database data.
• LOB types include BFILE, BLOB, CLOB,
and NCLOB
Printing in PL/SQL
• Procedures of DBMS_OUTPUT package is used
– DBMS_OUTPUT.PUT(string)
– DBMS_OUTPUT.PUT_LINE(string)
• Before using this package run the command
– SET SERVEROUTPUT ON
Writing and Executing PL/SQL Program
• Writing
– Write code in Notepad.
– SQL code files have extension .sql
• Executing
– Give following commands
• @ completefilename -OR-
• EXEC completefilename
Example: @d:mycodeaddition
-in the following line type / to execute
PL/SQL CONTROL STRUCTURE
1. Conditional Control Statement IF
Syntax 1:
IF condition
THEN
.....
END IF;
Syntax 2:
IF condition
THEN
.....
ELSE
.....
END IF;
1. Conditional Control Statement IF
Syntax 3:
IF condition
THEN
.....
ELSIF condition
THEN
.....
ELSIF condition
THEN
.....
ELSE
.....
END IF;
2. CASE Statement
• The CASE statement selects one sequence of
statements to execute.
CASE selector
WHEN value THEN ....
WHEN value THEN...
.....
ELSE .....
END CASE;
3. Using LOOP statement
LOOP
statement(s);
END LOOP;
• Force simple to stop using statements
EXIT;
EXIT WHEN <condition>;
4. While Loop
• The WHILE-LOOP statement executes the
statements in the loop body as long as a
condition is true.
WHILE condition
LOOP
sequence_of_statements
END LOOP;
5. FOR Loop
• FOR loops iterate over a specified range of
integers.
• A double dot (..) serves as the range operator
FOR loopvariable IN [REVERSE} lowest..highest
LOOP
<statement(s);
END LOOP;
DATABASE INTERACTION IN PL/SQL
• You can use following SQL statement in
PL/SQL code
– SELECT
– INSERT
– DELETE
– UPDATE
SELECT INTO statement
• SELECT INTO statement is used to store the
result in variable where PL/SQL access it and
manipulate it.
SELECT column_list INTO variable_list
FROM tablename
[WHERE condition]
Example: SELECT empno,salary INTO eno, sal
FROM employee WHERE empno=5;
4. plsql
4. plsql
4. plsql
SELECT INTO statement
• Where would you store data?????
SELECT * INTO ????????
FROM ....
....
• Solution
– Declare variable for each column
– USE records
USING RECORDS
Using RECORDS
• A record is a group of multiple piece of
information, related to one another called
fields.
• Types of Records
– Table Based Records
– Programmer Defined Records
– Cursor Based Records
Table Based Records
• Represents each fields of a table
• %ROWTYPE is used to declared table based
record.
record_name table_name%ROWTYPE;
• Example
emp_rec employee%ROWTYPE;
Table Based Records
• Accessing individual fields using dot(.)
record_name.field_name
Example:
SELECT * INTO emp_rec
FROM employee
WHERE empno=5
dbms_output.put_line(emp_rec.Name);
Programmer Based Record
• TYPE statement is used to defined
programmer defined record.
• Firstly RECORD type is defined with TYPE
statement then declare variable of RECORD
type.
TYPE <typename> IS RECORD
(fields declaration);
Programmer Based Record
• Example
declare
type empType IS RECORD
(eno number, ename varchar(20));
emp_rec empType;
begin
SELECT empno,name INTO emp_rec
....
end;
NOTE
• IF a SELECT INTO statement return more than
one rows, Oracle return ERROR message.
• Solution
– CURSOR
CURSORS IN PL/SQL
PL/SQL Cursor
• Cursor is a mechanism that provides a way to
select multiple rows of data from a table and
then process each row individually inside
PL/SQL block.
• Set of rows returned by multi row query is
called Result Set or Active Set.
– Context Area contain result set.
– Cursor is pointer to this context Area.
Types of Cursor
• Implicit Cursor
– Declared for all DML and SELECT that return one
row
• Explicit Cursor
– Used for queries that return more than one data.
– Declared and named by programmer.
Explicit Cursor
• Four Steps
1. Declare Cursor
• Declared in declaration part
CURSOR cursorname IS select statement
2. Open Cursor
• Activates query and identification of rows satisfy
query
OPEN cursorname;
Explicit Cursor
• Four Steps
3. Fetch Rows
• Retrieves rows individually
FETCH cursorname INTO record_list
4. Close Cursor
• Close the cursor and release the resources
CLOSE cursorname;
Explicit Cursor Attributes
• %NOTFOUND attribute
• %FOUND attribute
• %ROWCOUNT attribute
• %ISOPEN attribute
ADVANTAGES OF PL/SQL
• Support for SQL
• Better Performance
• Higher Productivity
• Full Portable
• Tight Integration with SQL
• Security

More Related Content

4. plsql

  • 2. What is PL/SQL? • PL/SQL is a block-structured language. • A block lets you group logically related declarations and statements.
  • 3. What is PL/SQL? • A PL/SQL block has three parts: – Optional DECLARATIVE part, – an executable part, and – Optional EXCEPTION-HANDLING part. [Block header] [DECLARE <constants> <variables> <cursors>] [BEGIN] <PL/SQL statements> [EXCEPTION exception handling routine>] END;
  • 4. Types of Block • Anonymous Block – Are blocks without header • Named Block – Blocks having headers – Can be either Subprogram or triggers – Can be compiled separately and stored permanently in an Oracle database, Ready to be executed
  • 5. Variables and Constant • Must declare a constant or variable before referencing it in other statements in a declarative part of the block • Declaring Variable variablename datatype[(size)] [:= initial value]
  • 6. Variables and Constant • Variable Declaration – Bound Declaration • Specify size for a variable • Example: age NUMBER(2); --store 2 digits – Unbound Declaration • Allocate maximum memory allowed for that particular type • Example: age NUMBER;
  • 7. Variables and Constant • Variable Declaration – Anchored Declaration • Variable is declared with another variable or a table column • %TYPE is used for anchor declaration. variablename object%TYPE[:= initial value] • Example: num1 NUMBER[5]; num2 num%TYPE; empsal EMPLOYEE.SALARY%TYPE;
  • 8. Variable and Constant • Assigning Values to a Variable – Assignment operator := is used to assign value to a variable. variablename:=<value/expression> • Commenting Your Code – Single Line Comment: starts with double ‘-’ – Multiple Line Comment: /*...*/
  • 9. Variables and Constants • Literal – It is a simply a value, which is not represented by an identifier • Constant – Named literal is called constant – Declaring Constant constant_name CONSTANT datatype[(size)] := initial value] Example: pi CONSTANT NUMBER:=3.14;
  • 11. PL/SQL Datatypes • Datatype identify type of data and associated operation for handling it. • PL/SQL provides – Scalar types – Composite types – Reference types – LOB types
  • 12. 1.Scalar Types • It is atomic. – Not made up of other dataypes. • It holds a single value, such as a number or character string. • Falls into four types – PL/SQL Number Types – PL/SQL Character and String Types – PL/SQL Boolean Types – PL/SQL Date, Time, and Interval Types
  • 13. 1.Scalar Types • PL/SQL Number Types – BINARY_DOUBLE, BINARY_FLOAT, BINARY_INTEGER, DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INT, INTEGER, NATURAL, NATURALN, NUMBER, NUMERIC, PLS_INTEGER, POSITIVE, POSITIVEN, REAL, SIGNTYPE, SMALLINT • PL/SQL Character and String Types – CHAR, CHARACTER, LONG, LONG RAW, NCHAR, NVARCHAR2, RAW, ROWID, STRING, UROWID, VARCHAR, VARCHAR2
  • 14. 1.Scalar Types • PL/SQL Boolean Types – BOOLEAN • PL/SQL Date, Time, and Interval Types – DATE, TIMESTAMP, TIMESTAMP WITH TIMEZONE, TIMESTAMP WITH LOCAL TIMEZONE, INTERVAL YEAR TO MONTH, INTERVAL DAY TOSECOND
  • 15. 2. Composite Type • Made up with other datatypes such as the elements of an ARRAY, RECORD, or TABLE.
  • 16. 3. Reference Datatypes • A reference type holds values, called pointers, that designate other program items. • Include REF CURSORS and REFs to object types.
  • 17. 4. LOB Types • A LOB type holds values, that specify the location of large objects, such as text blocks or graphic images, that are stored separately from other database data. • LOB types include BFILE, BLOB, CLOB, and NCLOB
  • 18. Printing in PL/SQL • Procedures of DBMS_OUTPUT package is used – DBMS_OUTPUT.PUT(string) – DBMS_OUTPUT.PUT_LINE(string) • Before using this package run the command – SET SERVEROUTPUT ON
  • 19. Writing and Executing PL/SQL Program • Writing – Write code in Notepad. – SQL code files have extension .sql • Executing – Give following commands • @ completefilename -OR- • EXEC completefilename Example: @d:mycodeaddition -in the following line type / to execute
  • 21. 1. Conditional Control Statement IF Syntax 1: IF condition THEN ..... END IF; Syntax 2: IF condition THEN ..... ELSE ..... END IF;
  • 22. 1. Conditional Control Statement IF Syntax 3: IF condition THEN ..... ELSIF condition THEN ..... ELSIF condition THEN ..... ELSE ..... END IF;
  • 23. 2. CASE Statement • The CASE statement selects one sequence of statements to execute. CASE selector WHEN value THEN .... WHEN value THEN... ..... ELSE ..... END CASE;
  • 24. 3. Using LOOP statement LOOP statement(s); END LOOP; • Force simple to stop using statements EXIT; EXIT WHEN <condition>;
  • 25. 4. While Loop • The WHILE-LOOP statement executes the statements in the loop body as long as a condition is true. WHILE condition LOOP sequence_of_statements END LOOP;
  • 26. 5. FOR Loop • FOR loops iterate over a specified range of integers. • A double dot (..) serves as the range operator FOR loopvariable IN [REVERSE} lowest..highest LOOP <statement(s); END LOOP;
  • 28. • You can use following SQL statement in PL/SQL code – SELECT – INSERT – DELETE – UPDATE
  • 29. SELECT INTO statement • SELECT INTO statement is used to store the result in variable where PL/SQL access it and manipulate it. SELECT column_list INTO variable_list FROM tablename [WHERE condition] Example: SELECT empno,salary INTO eno, sal FROM employee WHERE empno=5;
  • 33. SELECT INTO statement • Where would you store data????? SELECT * INTO ???????? FROM .... .... • Solution – Declare variable for each column – USE records
  • 35. Using RECORDS • A record is a group of multiple piece of information, related to one another called fields. • Types of Records – Table Based Records – Programmer Defined Records – Cursor Based Records
  • 36. Table Based Records • Represents each fields of a table • %ROWTYPE is used to declared table based record. record_name table_name%ROWTYPE; • Example emp_rec employee%ROWTYPE;
  • 37. Table Based Records • Accessing individual fields using dot(.) record_name.field_name Example: SELECT * INTO emp_rec FROM employee WHERE empno=5 dbms_output.put_line(emp_rec.Name);
  • 38. Programmer Based Record • TYPE statement is used to defined programmer defined record. • Firstly RECORD type is defined with TYPE statement then declare variable of RECORD type. TYPE <typename> IS RECORD (fields declaration);
  • 39. Programmer Based Record • Example declare type empType IS RECORD (eno number, ename varchar(20)); emp_rec empType; begin SELECT empno,name INTO emp_rec .... end;
  • 40. NOTE • IF a SELECT INTO statement return more than one rows, Oracle return ERROR message. • Solution – CURSOR
  • 42. PL/SQL Cursor • Cursor is a mechanism that provides a way to select multiple rows of data from a table and then process each row individually inside PL/SQL block. • Set of rows returned by multi row query is called Result Set or Active Set. – Context Area contain result set. – Cursor is pointer to this context Area.
  • 43. Types of Cursor • Implicit Cursor – Declared for all DML and SELECT that return one row • Explicit Cursor – Used for queries that return more than one data. – Declared and named by programmer.
  • 44. Explicit Cursor • Four Steps 1. Declare Cursor • Declared in declaration part CURSOR cursorname IS select statement 2. Open Cursor • Activates query and identification of rows satisfy query OPEN cursorname;
  • 45. Explicit Cursor • Four Steps 3. Fetch Rows • Retrieves rows individually FETCH cursorname INTO record_list 4. Close Cursor • Close the cursor and release the resources CLOSE cursorname;
  • 46. Explicit Cursor Attributes • %NOTFOUND attribute • %FOUND attribute • %ROWCOUNT attribute • %ISOPEN attribute
  • 48. • Support for SQL • Better Performance • Higher Productivity • Full Portable • Tight Integration with SQL • Security