SlideShare una empresa de Scribd logo
1 de 31
PL/SQL
PL/SQL
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;
/
Cont…..
If the SELECT statement identifies more than one row to be
fetched ,Oracle Database will raise the TOO_MANY_ROWS exception.
If the statement doesn’t identify any rows to be fetched, Oracle
Database will raise the NO_DATA_FOUND exception.
Here are some examples of using SELECT-INTO:
Get the last name for a specific employee ID (the primary key in the
employees table):
DECLARE l_last_name employees.last_name%TYPE; BEGIN SELECT
last_name INTO l_last_name FROM employees WHERE employee_id =
138; DBMS_OUTPUT.put_line ( l_last_name); END;
Fetch columns from different tables
– Fetch columns from different tables:
– DECLARE l_last_name employees.last_name%TYPE;
l_department_name departments.department_name%TYPE; BEGIN
SELECT last_name, department_name INTO l_last_name,
l_department_name FROM employees e, departments d WHERE
e.department_id=d.department_id AND e.employee_id=138;
DBMS_OUTPUT.put_line ( l_last_name || ' in ' ||
l_department_name); END;
%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
(predefine)
– Explicit cursors can be declared by a programmer within
PL/SQL. {jo programmer banata ha}
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
Cursor declaration
– 1) Declaring a Cursor in the Declaration Section:
– DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl
WHERE salary > 5000;
How to access an Explicit
Cursor?
• These are the three steps in accessing the cursor.
1) Open the cursor.
2) Fetch the records in the cursor one at a time.
3) Close the cursor.
• General Syntax to open a cursor is:
• OPEN cursor_name; General Syntax to fetch records from a
cursor is:
• FETCH cursor_name INTO record_name; OR
FETCH cursor_name INTO variable_list; General Syntax to
close a cursor is:
• CLOSE cursor_name;
Using Loops with Explicit
Cursors:
• Cursor with a Simple Loop:
• 1> DECLARE
• 2> CURSOR emp_cur IS
• 3> SELECT first_name, last_name, salary FROM emp_tbl;
• 4> emp_rec emp_cur%rowtype;
• 5> BEGIN
• 6> IF NOT sales_cur%ISOPEN THEN
• 7> OPEN sales_cur;
• 8> END IF;
• 9> LOOP
• 10> FETCH emp_cur INTO emp_rec;
• 11> EXIT WHEN emp_cur%NOTFOUND;
• 12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
• 13> || ' ' ||emp_cur.salary);
• 14> END LOOP;
• 15> END;
• 16> /
Cursor with a While
Loop:
• Lets modify the above program to use while loop.
• 1> DECLARE
• 2> CURSOR emp_cur IS
• 3> SELECT first_name, last_name, salary FROM emp_tbl;
• 4> emp_rec emp_cur%rowtype;
• 5> BEGIN
• 6> IF NOT sales_cur%ISOPEN THEN
• 7> OPEN sales_cur;
• 8> END IF;
• 9> FETCH sales_cur INTO sales_rec;
• 10> WHILE sales_cur%FOUND THEN
• 11> LOOP
• 12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
• 13> || ' ' ||emp_cur.salary);
• 14> FETCH sales_cur INTO sales_rec;
• 15> END LOOP;
• 16> END;
Cursor with a FOR Loop:
• When using FOR LOOP you need not declare a record
or variables to store the cursor values, need not open,
fetch and close the cursor. These functions are
accomplished by the FOR LOOP automatically.
• General Syntax for using FOR LOOP:
• FOR record_name IN cusror_name
• LOOP
• process the row...
• END LOOP;
• Let’s use the above example to learn how to use for loops in cursors.
• 1> DECLARE
• 2> CURSOR emp_cur IS
• 3> SELECT first_name, last_name, salary FROM emp_tbl;
• 4> emp_rec emp_cur%rowtype;
• 5> BEGIN
• 6> FOR emp_rec in sales_cur
• 7> LOOP
• 8> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name 9> || ' ' ||emp_cur.salary);
• 10> END LOOP;
• 11>END;
• 12> /
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
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;
/
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)

Más contenido relacionado

La actualidad más candente

Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-PresentationChuck Walker
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptionsrehaniltifat
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)pptGowarthini
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQLKailash N
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBaseSalman Memon
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals INick Buytaert
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Developmentrehaniltifat
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependenciesrehaniltifat
 

La actualidad más candente (20)

PL/SQL
PL/SQLPL/SQL
PL/SQL
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQL
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
8. sql
8. sql8. sql
8. sql
 
4. plsql
4. plsql4. plsql
4. plsql
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
SQL
SQLSQL
SQL
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 

Similar a Plsql (20)

SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
PLSQL
PLSQLPLSQL
PLSQL
 
4. plsql 1
4. plsql 14. plsql 1
4. plsql 1
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06
 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 
plsql.ppt
plsql.pptplsql.ppt
plsql.ppt
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
4 cursors
4 cursors4 cursors
4 cursors
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
Verilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONSVerilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONS
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
 
Pl sql
Pl sqlPl sql
Pl sql
 
Day 6.pptx
Day 6.pptxDay 6.pptx
Day 6.pptx
 
as
asas
as
 

Más de fika sweety

Query optimization and performance
Query optimization and performanceQuery optimization and performance
Query optimization and performancefika sweety
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
Modeling and simulation ch 1
Modeling and simulation ch 1Modeling and simulation ch 1
Modeling and simulation ch 1fika sweety
 
Macros...presentation
Macros...presentationMacros...presentation
Macros...presentationfika sweety
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchartfika sweety
 
Howtowriteamemo 090920105907-phpapp02
Howtowriteamemo 090920105907-phpapp02Howtowriteamemo 090920105907-phpapp02
Howtowriteamemo 090920105907-phpapp02fika sweety
 
Coal presentationt
Coal presentationtCoal presentationt
Coal presentationtfika sweety
 
1 Computer Architecture
1 Computer Architecture1 Computer Architecture
1 Computer Architecturefika sweety
 
Warehouse chapter3
Warehouse chapter3   Warehouse chapter3
Warehouse chapter3 fika sweety
 
Query optimization and performance
Query optimization and performanceQuery optimization and performance
Query optimization and performancefika sweety
 
Database security copy
Database security   copyDatabase security   copy
Database security copyfika sweety
 

Más de fika sweety (20)

Query optimization and performance
Query optimization and performanceQuery optimization and performance
Query optimization and performance
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
Shift rotate
Shift rotateShift rotate
Shift rotate
 
Graphss
GraphssGraphss
Graphss
 
Modeling and simulation ch 1
Modeling and simulation ch 1Modeling and simulation ch 1
Modeling and simulation ch 1
 
Macros...presentation
Macros...presentationMacros...presentation
Macros...presentation
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
Diversity (HRM)
Diversity (HRM)Diversity (HRM)
Diversity (HRM)
 
Howtowriteamemo 090920105907-phpapp02
Howtowriteamemo 090920105907-phpapp02Howtowriteamemo 090920105907-phpapp02
Howtowriteamemo 090920105907-phpapp02
 
Coal presentationt
Coal presentationtCoal presentationt
Coal presentationt
 
1 Computer Architecture
1 Computer Architecture1 Computer Architecture
1 Computer Architecture
 
3 Pipelining
3 Pipelining3 Pipelining
3 Pipelining
 
19 primkruskal
19 primkruskal19 primkruskal
19 primkruskal
 
Warehouse chapter3
Warehouse chapter3   Warehouse chapter3
Warehouse chapter3
 
Storage memory
Storage memoryStorage memory
Storage memory
 
Quick sort
Quick sortQuick sort
Quick sort
 
Query optimization and performance
Query optimization and performanceQuery optimization and performance
Query optimization and performance
 
L2
L2L2
L2
 
Master theorem
Master theoremMaster theorem
Master theorem
 
Database security copy
Database security   copyDatabase security   copy
Database security copy
 

Último

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 

Último (20)

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

Plsql

  • 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.
  • 8. 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.
  • 9. 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 ;
  • 10. 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 /
  • 11. 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; /
  • 12. 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
  • 13. 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
  • 14. 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; /
  • 15. Cont….. If the SELECT statement identifies more than one row to be fetched ,Oracle Database will raise the TOO_MANY_ROWS exception. If the statement doesn’t identify any rows to be fetched, Oracle Database will raise the NO_DATA_FOUND exception. Here are some examples of using SELECT-INTO: Get the last name for a specific employee ID (the primary key in the employees table): DECLARE l_last_name employees.last_name%TYPE; BEGIN SELECT last_name INTO l_last_name FROM employees WHERE employee_id = 138; DBMS_OUTPUT.put_line ( l_last_name); END;
  • 16. Fetch columns from different tables – Fetch columns from different tables: – DECLARE l_last_name employees.last_name%TYPE; l_department_name departments.department_name%TYPE; BEGIN SELECT last_name, department_name INTO l_last_name, l_department_name FROM employees e, departments d WHERE e.department_id=d.department_id AND e.employee_id=138; DBMS_OUTPUT.put_line ( l_last_name || ' in ' || l_department_name); END;
  • 17. %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; /
  • 18. 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 (predefine) – Explicit cursors can be declared by a programmer within PL/SQL. {jo programmer banata ha}
  • 19. 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
  • 20. 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
  • 21. Cursor declaration – 1) Declaring a Cursor in the Declaration Section: – DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000;
  • 22. How to access an Explicit Cursor? • These are the three steps in accessing the cursor. 1) Open the cursor. 2) Fetch the records in the cursor one at a time. 3) Close the cursor. • General Syntax to open a cursor is: • OPEN cursor_name; General Syntax to fetch records from a cursor is: • FETCH cursor_name INTO record_name; OR FETCH cursor_name INTO variable_list; General Syntax to close a cursor is: • CLOSE cursor_name;
  • 23. Using Loops with Explicit Cursors: • Cursor with a Simple Loop: • 1> DECLARE • 2> CURSOR emp_cur IS • 3> SELECT first_name, last_name, salary FROM emp_tbl; • 4> emp_rec emp_cur%rowtype; • 5> BEGIN • 6> IF NOT sales_cur%ISOPEN THEN • 7> OPEN sales_cur; • 8> END IF; • 9> LOOP • 10> FETCH emp_cur INTO emp_rec; • 11> EXIT WHEN emp_cur%NOTFOUND; • 12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name • 13> || ' ' ||emp_cur.salary); • 14> END LOOP; • 15> END; • 16> /
  • 24. Cursor with a While Loop: • Lets modify the above program to use while loop. • 1> DECLARE • 2> CURSOR emp_cur IS • 3> SELECT first_name, last_name, salary FROM emp_tbl; • 4> emp_rec emp_cur%rowtype; • 5> BEGIN • 6> IF NOT sales_cur%ISOPEN THEN • 7> OPEN sales_cur; • 8> END IF; • 9> FETCH sales_cur INTO sales_rec; • 10> WHILE sales_cur%FOUND THEN • 11> LOOP • 12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name • 13> || ' ' ||emp_cur.salary); • 14> FETCH sales_cur INTO sales_rec; • 15> END LOOP; • 16> END;
  • 25. Cursor with a FOR Loop: • When using FOR LOOP you need not declare a record or variables to store the cursor values, need not open, fetch and close the cursor. These functions are accomplished by the FOR LOOP automatically. • General Syntax for using FOR LOOP: • FOR record_name IN cusror_name • LOOP • process the row... • END LOOP;
  • 26. • Let’s use the above example to learn how to use for loops in cursors. • 1> DECLARE • 2> CURSOR emp_cur IS • 3> SELECT first_name, last_name, salary FROM emp_tbl; • 4> emp_rec emp_cur%rowtype; • 5> BEGIN • 6> FOR emp_rec in sales_cur • 7> LOOP • 8> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name 9> || ' ' ||emp_cur.salary); • 10> END LOOP; • 11>END; • 12> /
  • 27. 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; /
  • 28. 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; /
  • 29. 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
  • 30. 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; /
  • 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)