SlideShare une entreprise Scribd logo
1  sur  31
PL/SQL
By :
Bharat Kalia
What is PL/SQL
• Procedural Language – SQL
• An extension to SQL with design features
of programming languages (procedural and
object oriented)
• PL/SQL and Java are both supported as
internal host languages within Oracle
products.
Why PL/SQL
• Acts as host language for stored procedures
and triggers.
• Provides the ability to add middle tier
business logic to client/server applications.
• Provides Portability of code from one
environment to another
• Improves performance of multi-query
transactions.
• Provides error handling
PL/SQL BLOCK STRUCTURE
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
EXCEPTION (optional)
- actions to perform when errors occur
END; (required)
PL/SQL Block Types
Anonymous
DECLARE
BEGIN
-statements
EXCEPTION
END;
Procedure
PROCEDURE <name>
IS
BEGIN
-statements
EXCEPTION
END;
Function
FUNCTION <name>
RETURN <datatype>
IS
BEGIN
-statements
EXCEPTION
END;
PL/SQL Variable Types
• Scalar (char, varchar2, number, date, etc)
• Composite (%rowtype)
• Reference (pointers)
• LOB (large objects)
Note: Non PL/SQL variables include bind variables,
host (“global”) variables, and parameters.
Variable Naming Conventions
• Two variables can have the same name if
they are in different blocks (bad idea)
• The variable name should not be the same
as any table column names used in the
block.
PL/SQL is strongly typed
• All variables must be declared before their
use.
• The assignment statement
: =
is not the same as the equality operator
=
• All statements end with a ;
PL/SQL Sample Program
Variable g_inv_value number
DECLARE
v_price number(8,2) := 10.25;
v_quantity number(8,0) := 400;
BEGIN
:g_inv_value := v_price * v_quantity;
END;
/
Print g_inv_value
/
PL/SQL Sample Program
Set serveroutput on
DECLARE
v_inv_value number(10,2);
v_price number(8,2) := 10.25;
v_quantity number(8,0) := 400;
BEGIN
v_inv_value := v_price * v_quantity;
dbms_output.put('The value is: ');
dbms_output.put_line(v_inv_value);
END;
/
PL/SQL Sample Program
(with user input)
Set serveroutput on
Accept p_price Prompt 'Enter the Price: '
DECLARE
v_inv_value number(8,2);
v_price number(8,2);
v_quantity number(8,0) := 400;
BEGIN
v_price := &p_price;
v_inv_value := v_price * v_quantity;
dbms_output.put_line('******');
dbms_output.put_line('price * quantity=');
dbms_output.put_line(v_inv_value);
END;
/
Note: PL/SQL not designed for user interface programming
PL/SQL Comments
DECLARE
v_salary number(9,2) := 40000;
BEGIN
/* this is a multi-line comment that
will be ignored by the pl/sql
interpreter */
v_salary := v_salary * 2; -- nice raise
END; -- end of program
SELECT INTO
SET SERVEROUTPUT ON
DECLARE
v_max_gpa number(3,2);
v_numstudents number(4);
v_lname students.lname%type;
v_major students.major%type;
BEGIN
select max(gpa) into v_max_gpa
from students;
DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa);
select count(sid) into v_numstudents
from students
where gpa = v_max_gpa;
IF v_numstudents > 1 then
DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA');
ELSE
select lname, major into v_lname, v_major
from students
where gpa=v_max_gpa;
DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname);
DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major);
END IF;
END;
COMMON PL/SQL STRING FUNCTIONS
• CHR(asciivalue)
• ASCII(string)
• LOWER(string)
• SUBSTR(string,start,substrlength)
• LTRIM(string)
• RTRIM(string)
• LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
• RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
• REPLACE(string, searchstring, replacestring)
• UPPER(string)
• INITCAP(string)
• LENGTH(string)
COMMON PL/SQL NUMERIC FUNCTIONS
• ABS(value)
• ROUND(value, precision)
• MOD(value,divisor)
• SQRT(value)
• TRUNC(value,|precision|)
• LEAST(exp1, exp2…)
• GREATEST(exp1, exp2…)
%ROWTYPE
Set serveroutput on
DECLARE
v_student students%rowtype;
BEGIN
select * into v_student
from students
where sid='123456';
DBMS_OUTPUT.PUT_LINE (v_student.lname);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE (v_student.gpa);
END;
/
CURSORS
• A cursor is a private set of records
• An Oracle Cursor = VB recordset = JDBC
ResultSet
• Implicit cursors are created for every query
made in Oracle
• Explicit cursors can be declared by a
programmer within PL/SQL.
Cursor Attributes
• cursorname%ROWCOUNT Rows returned so far
• cursorname%FOUND One or more rows retrieved
• cursorname%NOTFOUND No rows found
• Cursorname%ISOPEN Is the cursor open
Explicit Cursor Control
• Declare the cursor
• Open the cursor
• Fetch a row
• Test for end of cursor
• Close the cursor
Note: there is a FOR LOOP available with an implicit fetch
Sample Cursor Program
DECLARE
CURSOR students_cursor IS
SELECT * from students;
v_student students_cursor%rowtype;
/* instead we could do v_student students%rowtype */
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_student;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_student.last);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_student;
END LOOP;
CLOSE students_cursor;
END;
/
Sample Cursor Program
(same program without composite variable)
DECLARE
CURSOR students_cursor IS
SELECT last, major from students;
v_Last students.last%type;
v_major students.major%type;
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_last, v_major;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_last);
DBMS_OUTPUT.PUT_LINE (v_major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_last, v_major;
END LOOP;
CLOSE students_cursor;
END;
/
When is PL/SQL handy
• When something is too complicated for SQL
• When conditional branching and looping are needed
• Example
• Write a PL/SQL program that assigns email address to each employee or
student in a table. Following these rules:
- email address should be all lower case
- email address should default to first initial plus the first seven letters of the last name
- email can be no longer than eight characters
- if email is already used than use first initial plus middle initial plus first
six letters of last name
- if the previous address is taken use the first two letters of the first name
and the first six letters of the last name.
- if the previous address is taken use first six letters of last name + 01 or 02 …etc
Stored Procedures
• PL/SQL code stored in the database and executed when called by the user.
• Called by procedure name from another PL/SQL block or using EXECUTE
from SQL+. For example EXEC SQR(50)
• Example:
Create procedure SQR (v_num_to_square IN number)
AS
v_answer number(10);
BEGIN
v_answer := v_num_to_square * v_num_to_square;
dbms_output.put_line(v_answer);
END;
/
Function
• PL/SQL user defined function stored in the database and executed when a
function call is made in code: example x := SQUARED(50)
• Example:
Create or Replace Function SQUARED
(p_number_to_square IN number)
RETURN number
IS
v_answer number(10);
BEGIN
v_answer := p_number_to_square * p_number_to_square;
RETURN(v_answer);
END;
/
Another Stored Procedure Example
Create or replace procedure mytabs
AS
CURSOR table_cursor IS
Select table_name from user_tables;
v_tablename varchar2(30);
BEGIN
open table_cursor;
fetch table_cursor into v_tablename;
while table_cursor%found loop
dbms_output.put_line(v_tablename);
fetch table_cursor into v_tablename;
end loop;
close table_cursor;
END;
Triggers
• PL/SQL code executed automatically in response to a database event, typically
DML.
• Like other stored procedures, triggers are stored in the database.
• Often used to:
– enforce complex constraints, especially multi-table constraints. Financial posting
is an example of this.
– Trigger related actions
– implement auditing “logs”
– pop a sequence when creating token keys
• Triggers do not issue transaction control statements (such as commit).
Triggers are part of the SQL transaction that invoked them.
• USER_TRIGGERS provides a data dictionary view of triggers.
Triggers
CREATE OR REPLACE TRIGGER <trigger_name>
[BEFORE/AFTER][DELETE/INSERT/UPDATE of <column_name |, column_name… |>
ON <table_name>
|FOR EACH ROW|
|WHEN <triggering condition>|
|DECLARE|
BEGIN
trigger statements
…………
END;
To delete a trigger use:
DROP TRIGGER <trigger_name>;
Log Trigger Example
CREATE OR REPLACE TRIGGER LOGSTUDENTCHANGES
BEFORE INSERT OR DELETE OR UPDATE of Major ON STUDENTS
FOR EACH ROW
DECLARE
v_ChangeType CHAR(1);
v_sid varchar2(10);
BEGIN
IF INSERTING THEN
V_ChangeType := 'I';
v_sid := :new.sid;
ELSIF UPDATING THEN
V_ChangeType := 'U';
v_sid := :new.sid;
ELSE
V_ChangeType := 'D';
v_sid := :old.sid;
END IF;
INSERT INTO MAJ_AUDIT (change_type, changed_by, timestamp,
SID, old_major, new_major)
VALUES (v_ChangeType, USER, SYSDATE, v_sid, :old.major, :new.major);
END LOGSTUDENTCHANGES;
UpperCase Trigger Example
CREATE OR REPLACE TRIGGER UPPERCASE
BEFORE INSERT OR UPDATE ON STUDENTS
FOR EACH ROW
DECLARE
BEGIN
:new.lastname:=UPPER(:new.lastname);
:new.firstname:=UPPER(:new.firstname);
END UPPERCASE;
/
Ben & Jerry Trigger Example
(no employee can make more than 10 times as much as the lowest paid employee)
CREATE OR REPLACE TRIGGER SalaryTrig
BEFORE INSERT ON Employees
FOR EACH ROW
DECLARE
v_upper_sal_limit NUMBER(10,2);
v_lower_sal_limit NUMBER(10,2);
BEGIN
SELECT MIN(salary)*10 INTO v_upper_sal_limit
FROM employees;
SELECT MAX(salary)/10 INTO v_lower_sal_limit
FROM employees;
IF :new.salary NOT BETWEEN v_lower_sal_limit AND v_upper_sal_limit THEN
RAISE_APPLICATION_ERROR(-20001,'salary out of allowed range');
END IF;
END SalaryTrig;
/
Notes: Application error number is a parameter between –20,000 and –20,999.
You could also stop the insert by "poisoning" it, changing a :new
buffer value to one that you know will not pass constraint evaluation.
SEQUENCE
CREATE SEQUENCE <sequence_name>
|INCREMENT BY <number>|
|START WITH <start_value>|
|MAXVALUE <maximum_value>|NOMAXVALUE|
|MINVALUE <minimum_value>|
|CYCLE|NOCYLE|
|CACHE <number of values>|NOCACHE|
|ORDER|NOORDER|
To pop the next sequence use:
SEQUENCENAME.NEXTVAL (CURRVAL shows last pop)

Contenu connexe

Tendances (20)

4. plsql
4. plsql4. plsql
4. plsql
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Unit 5 composite datatypes
Unit 5  composite datatypesUnit 5  composite datatypes
Unit 5 composite datatypes
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
SQL
SQLSQL
SQL
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Sql joins
Sql joinsSql joins
Sql joins
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 

Similaire à PL/SQL Introduction and Concepts

Similaire à PL/SQL Introduction and Concepts (20)

PLSQL
PLSQLPLSQL
PLSQL
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
Plsql
PlsqlPlsql
Plsql
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
plsql.ppt
plsql.pptplsql.ppt
plsql.ppt
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
4. plsql 1
4. plsql 14. plsql 1
4. plsql 1
 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 
Module04
Module04Module04
Module04
 
Stored procedures and cursors
Stored procedures and cursorsStored procedures and cursors
Stored procedures and cursors
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
 
Stored procedure with cursor
Stored procedure with cursorStored procedure with cursor
Stored procedure with cursor
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 

Plus de Bharat Kalia

Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project ReportBharat Kalia
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingBharat Kalia
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingBharat Kalia
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking SystemBharat Kalia
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR RecognitionBharat Kalia
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++ Bharat Kalia
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 

Plus de Bharat Kalia (10)

Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project Report
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific Computing
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking System
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR Recognition
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 

Dernier

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Dernier (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

PL/SQL Introduction and Concepts

  • 2. What is PL/SQL • Procedural Language – SQL • An extension to SQL with design features of programming languages (procedural and object oriented) • PL/SQL and Java are both supported as internal host languages within Oracle products.
  • 3. Why PL/SQL • Acts as host language for stored procedures and triggers. • Provides the ability to add middle tier business logic to client/server applications. • Provides Portability of code from one environment to another • Improves performance of multi-query transactions. • Provides error handling
  • 4. PL/SQL BLOCK STRUCTURE DECLARE (optional) - variable declarations BEGIN (required) - SQL statements - PL/SQL statements or sub-blocks EXCEPTION (optional) - actions to perform when errors occur END; (required)
  • 5. PL/SQL Block Types Anonymous DECLARE BEGIN -statements EXCEPTION END; Procedure PROCEDURE <name> IS BEGIN -statements EXCEPTION END; Function FUNCTION <name> RETURN <datatype> IS BEGIN -statements EXCEPTION END;
  • 6. PL/SQL Variable Types • Scalar (char, varchar2, number, date, etc) • Composite (%rowtype) • Reference (pointers) • LOB (large objects) Note: Non PL/SQL variables include bind variables, host (“global”) variables, and parameters.
  • 7. Variable Naming Conventions • Two variables can have the same name if they are in different blocks (bad idea) • The variable name should not be the same as any table column names used in the block.
  • 8. PL/SQL is strongly typed • All variables must be declared before their use. • The assignment statement : = is not the same as the equality operator = • All statements end with a ;
  • 9. PL/SQL Sample Program Variable g_inv_value number DECLARE v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN :g_inv_value := v_price * v_quantity; END; / Print g_inv_value /
  • 10. PL/SQL Sample Program Set serveroutput on DECLARE v_inv_value number(10,2); v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN v_inv_value := v_price * v_quantity; dbms_output.put('The value is: '); dbms_output.put_line(v_inv_value); END; /
  • 11. PL/SQL Sample Program (with user input) Set serveroutput on Accept p_price Prompt 'Enter the Price: ' DECLARE v_inv_value number(8,2); v_price number(8,2); v_quantity number(8,0) := 400; BEGIN v_price := &p_price; v_inv_value := v_price * v_quantity; dbms_output.put_line('******'); dbms_output.put_line('price * quantity='); dbms_output.put_line(v_inv_value); END; / Note: PL/SQL not designed for user interface programming
  • 12. PL/SQL Comments DECLARE v_salary number(9,2) := 40000; BEGIN /* this is a multi-line comment that will be ignored by the pl/sql interpreter */ v_salary := v_salary * 2; -- nice raise END; -- end of program
  • 13. SELECT INTO SET SERVEROUTPUT ON DECLARE v_max_gpa number(3,2); v_numstudents number(4); v_lname students.lname%type; v_major students.major%type; BEGIN select max(gpa) into v_max_gpa from students; DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa); select count(sid) into v_numstudents from students where gpa = v_max_gpa; IF v_numstudents > 1 then DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA'); ELSE select lname, major into v_lname, v_major from students where gpa=v_max_gpa; DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname); DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major); END IF; END;
  • 14. COMMON PL/SQL STRING FUNCTIONS • CHR(asciivalue) • ASCII(string) • LOWER(string) • SUBSTR(string,start,substrlength) • LTRIM(string) • RTRIM(string) • LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) • RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) • REPLACE(string, searchstring, replacestring) • UPPER(string) • INITCAP(string) • LENGTH(string)
  • 15. COMMON PL/SQL NUMERIC FUNCTIONS • ABS(value) • ROUND(value, precision) • MOD(value,divisor) • SQRT(value) • TRUNC(value,|precision|) • LEAST(exp1, exp2…) • GREATEST(exp1, exp2…)
  • 16. %ROWTYPE Set serveroutput on DECLARE v_student students%rowtype; BEGIN select * into v_student from students where sid='123456'; DBMS_OUTPUT.PUT_LINE (v_student.lname); DBMS_OUTPUT.PUT_LINE (v_student.major); DBMS_OUTPUT.PUT_LINE (v_student.gpa); END; /
  • 17. CURSORS • A cursor is a private set of records • An Oracle Cursor = VB recordset = JDBC ResultSet • Implicit cursors are created for every query made in Oracle • Explicit cursors can be declared by a programmer within PL/SQL.
  • 18. Cursor Attributes • cursorname%ROWCOUNT Rows returned so far • cursorname%FOUND One or more rows retrieved • cursorname%NOTFOUND No rows found • Cursorname%ISOPEN Is the cursor open
  • 19. Explicit Cursor Control • Declare the cursor • Open the cursor • Fetch a row • Test for end of cursor • Close the cursor Note: there is a FOR LOOP available with an implicit fetch
  • 20. Sample Cursor Program DECLARE CURSOR students_cursor IS SELECT * from students; v_student students_cursor%rowtype; /* instead we could do v_student students%rowtype */ BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_student; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_student.last); DBMS_OUTPUT.PUT_LINE (v_student.major); DBMS_OUTPUT.PUT_LINE ('******************'); FETCH students_cursor into v_student; END LOOP; CLOSE students_cursor; END; /
  • 21. Sample Cursor Program (same program without composite variable) DECLARE CURSOR students_cursor IS SELECT last, major from students; v_Last students.last%type; v_major students.major%type; BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_last, v_major; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_last); DBMS_OUTPUT.PUT_LINE (v_major); DBMS_OUTPUT.PUT_LINE ('******************'); FETCH students_cursor into v_last, v_major; END LOOP; CLOSE students_cursor; END; /
  • 22. When is PL/SQL handy • When something is too complicated for SQL • When conditional branching and looping are needed • Example • Write a PL/SQL program that assigns email address to each employee or student in a table. Following these rules: - email address should be all lower case - email address should default to first initial plus the first seven letters of the last name - email can be no longer than eight characters - if email is already used than use first initial plus middle initial plus first six letters of last name - if the previous address is taken use the first two letters of the first name and the first six letters of the last name. - if the previous address is taken use first six letters of last name + 01 or 02 …etc
  • 23. Stored Procedures • PL/SQL code stored in the database and executed when called by the user. • Called by procedure name from another PL/SQL block or using EXECUTE from SQL+. For example EXEC SQR(50) • Example: Create procedure SQR (v_num_to_square IN number) AS v_answer number(10); BEGIN v_answer := v_num_to_square * v_num_to_square; dbms_output.put_line(v_answer); END; /
  • 24. Function • PL/SQL user defined function stored in the database and executed when a function call is made in code: example x := SQUARED(50) • Example: Create or Replace Function SQUARED (p_number_to_square IN number) RETURN number IS v_answer number(10); BEGIN v_answer := p_number_to_square * p_number_to_square; RETURN(v_answer); END; /
  • 25. Another Stored Procedure Example Create or replace procedure mytabs AS CURSOR table_cursor IS Select table_name from user_tables; v_tablename varchar2(30); BEGIN open table_cursor; fetch table_cursor into v_tablename; while table_cursor%found loop dbms_output.put_line(v_tablename); fetch table_cursor into v_tablename; end loop; close table_cursor; END;
  • 26. Triggers • PL/SQL code executed automatically in response to a database event, typically DML. • Like other stored procedures, triggers are stored in the database. • Often used to: – enforce complex constraints, especially multi-table constraints. Financial posting is an example of this. – Trigger related actions – implement auditing “logs” – pop a sequence when creating token keys • Triggers do not issue transaction control statements (such as commit). Triggers are part of the SQL transaction that invoked them. • USER_TRIGGERS provides a data dictionary view of triggers.
  • 27. Triggers CREATE OR REPLACE TRIGGER <trigger_name> [BEFORE/AFTER][DELETE/INSERT/UPDATE of <column_name |, column_name… |> ON <table_name> |FOR EACH ROW| |WHEN <triggering condition>| |DECLARE| BEGIN trigger statements ………… END; To delete a trigger use: DROP TRIGGER <trigger_name>;
  • 28. Log Trigger Example CREATE OR REPLACE TRIGGER LOGSTUDENTCHANGES BEFORE INSERT OR DELETE OR UPDATE of Major ON STUDENTS FOR EACH ROW DECLARE v_ChangeType CHAR(1); v_sid varchar2(10); BEGIN IF INSERTING THEN V_ChangeType := 'I'; v_sid := :new.sid; ELSIF UPDATING THEN V_ChangeType := 'U'; v_sid := :new.sid; ELSE V_ChangeType := 'D'; v_sid := :old.sid; END IF; INSERT INTO MAJ_AUDIT (change_type, changed_by, timestamp, SID, old_major, new_major) VALUES (v_ChangeType, USER, SYSDATE, v_sid, :old.major, :new.major); END LOGSTUDENTCHANGES;
  • 29. UpperCase Trigger Example CREATE OR REPLACE TRIGGER UPPERCASE BEFORE INSERT OR UPDATE ON STUDENTS FOR EACH ROW DECLARE BEGIN :new.lastname:=UPPER(:new.lastname); :new.firstname:=UPPER(:new.firstname); END UPPERCASE; /
  • 30. Ben & Jerry Trigger Example (no employee can make more than 10 times as much as the lowest paid employee) CREATE OR REPLACE TRIGGER SalaryTrig BEFORE INSERT ON Employees FOR EACH ROW DECLARE v_upper_sal_limit NUMBER(10,2); v_lower_sal_limit NUMBER(10,2); BEGIN SELECT MIN(salary)*10 INTO v_upper_sal_limit FROM employees; SELECT MAX(salary)/10 INTO v_lower_sal_limit FROM employees; IF :new.salary NOT BETWEEN v_lower_sal_limit AND v_upper_sal_limit THEN RAISE_APPLICATION_ERROR(-20001,'salary out of allowed range'); END IF; END SalaryTrig; / Notes: Application error number is a parameter between –20,000 and –20,999. You could also stop the insert by "poisoning" it, changing a :new buffer value to one that you know will not pass constraint evaluation.
  • 31. SEQUENCE CREATE SEQUENCE <sequence_name> |INCREMENT BY <number>| |START WITH <start_value>| |MAXVALUE <maximum_value>|NOMAXVALUE| |MINVALUE <minimum_value>| |CYCLE|NOCYLE| |CACHE <number of values>|NOCACHE| |ORDER|NOORDER| To pop the next sequence use: SEQUENCENAME.NEXTVAL (CURRVAL shows last pop)