0% found this document useful (0 votes)
7 views

PLSQL

Uploaded by

sujithap388
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PLSQL

Uploaded by

sujithap388
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

PL/SQL

[Chennai],
[30/01/2023] - [03-02-2023]
Agenda

1 Getting Started with PL/SQL


5 Packages

2 Conditional Control, Loops, select


into, Exception handlers 6 Triggers

3 Records, Cursors
7 Collections

4 Stored Procedures,
Functions, Packages 8 Autonomous Transactions,
Dynamic SQL

2
Introduction to PL/SQL

PL/SQL stands for “Procedural Language extensions to the Structured Query Language”. SQL is a popular
language for both querying and updating data in the relational database management systems (RDBMS).
PL/SQL adds many procedural constructs to SQL language to overcome some limitations of SQL. Besides,
PL/SQL provides a more comprehensive programming language solution for building mission-critical
applications on Oracle Databases.

3
PL/SQL Architecture
PL/SQL Architecture

4
PL/SQL Anonymous Block
PL/SQL Anonymous Block

5
SELECT INTO
PL/SQL SELECT INTO examples

Let’s use the customers and contacts tables in the sample database for demonstration.

6
PL/SQL Cursor
A cursor is a pointer that points to a result of a query. PL/SQL has two types of cursors: implicit cursors and
explicit cursors.

7
PL/SQL Cursor
PL/SQL cursor example
We will use the orders and order_items tables from the sample database for the demonstration.

8
PL/SQL Procedure
A PL/SQL procedure is a reusable unit that encapsulates specific business logic of the application.
Technically speaking, a PL/SQL procedure is a named block stored as a schema object in the Oracle
Database.

Syntax of creating a procedure in PL/SQL:

CREATE [OR REPLACE ] PROCEDURE procedure_name (parameter_list)


IS

[declaration statements]
BEGIN
[execution statements]
EXCEPTION
[exception handler]
END [procedure_name ];

9
PL/SQL Function
PL/SQL function is a reusable program unit stored as a schema object in the Oracle Database. The
following illustrates the syntax for creating a function:

CREATE [OR REPLACE] FUNCTION function_name (parameter_list)


RETURN return_type
IS

[declarative section]
BEGIN
[executable section]
[EXCEPTION]
[exception-handling section]
END;

10
What is a PL/SQL package?
A package is a schema object that contains definitions for a group of related functionalities. A package
includes variables, constants, cursors, exceptions, procedures, functions, and subprograms. It is compiled
and stored in the Oracle Database.

11
Why PACKAGE?

Make code more modular

Hide implementation details

Improve application performance

Minimize unnecessary recompiling code

Manage authorization easily

12
PL/SQL - PACKAGE

A PL/SQL package has two parts: package specification and package body.

A package specification does not contain any implementations of the public items. For example, in case
of procedures or functions, the package specification contains only their headers, but not their bodies.
A package specification can exist independently if their items do not require implementations.

Typically, a package specification contains the following items:

Procedures
Functions
Cursors
Types, variables, and constants
Records
CollectionsSQL is a tool for organizing, managing, and retrieving data stored by a computer database.

13
Triggers
A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized
category of stored procedure that is called automatically when a database server event occurs. Each trigger is
always associated with a table.

The following are the main characteristics that distinguish triggers from stored procedures:

We cannot manually execute/invoked triggers.


Triggers have no chance of receiving parameters.
A transaction cannot be committed or rolled back inside a trigger.

When we use triggers?

Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios.

14
Triggers

Types of SQL Server Triggers

1.Data Definition Language (DDL) Triggers


2.Data Manipulation Language (DML) Triggers
3.Logon Triggers

15
Triggers
DML Triggers - Two Triggers
After Triggers
Instead Of Triggers

16
Triggers
After Triggers

We can classify this trigger further into three types:


1.AFTER INSERT Trigger
2.AFTER UPDATE Trigger
3.AFTER DELETE Trigger

17
Triggers
Instead of Triggers

We can classify this trigger further into three types:


1.INSTEAD OF INSERT Trigger
2.INSTEAD OF UPDATE Trigger
3.INSTEAD OF DELETE Trigger

18
Triggers
Logon Triggers

Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is
generated with an SQL Server instance, which is made after the authentication process of logging is completed
but before establishing a user session.

19
PL/SQL Collections
PL/SQL Associative Array
PL/SQL Associative Array
PL/SQL Associative Array
Associative arrays are single-dimensional, unbounded, sparse collections of homogeneous elements.

First, an associative array is single-dimensional. It means that an associative array has a single column of data
in each row, which is similar to a one-dimension array.

Second, an associative array is unbounded, meaning that it has a predetermined limits number of elements.

Third, an associative array is sparse because its elements are not sequential. In other words, an associative
array may have gaps between elements.

20
PL/SQL Coding Guidelines

Packages and Procedures

All PL/SQL functions and procedures will be implemented as part of a package. The package
names used will be specified in the component specification.

Source Files

Package headers and bodies will be declared in separate files. Package header file names will
use the ‘pkg’ extension. Package body file names will use the ‘.pkb’ extension.
Trigger code will be declared in a single file with the extension ‘.trg’.

21
PL/SQL Coding Guidelines
Header Comments
Package header source files will contain a package level comment which includes the following
information: FileName, Component Name, Description, Package Name, Designer Name,
Developer Name, Version, Date and Copyright statement. The format below will be followed
exactly.
/**********************************************************************
/*
/* Filename: TopCoder_Unit_Test.pkg
/* Component: Unit_Test_Framework
/* Package: Unit_Test_Frmwrk
/* Designer: TCSDesigner
/* Developer: TCSDeveloper
/* Version: 1.0
/* Copyright (c) 2006, TopCoder, Inc. All rights reserved.
/*
/* Description: Description of PL/SQL package...
/*
/**********************************************************************

22
PL/SQL Coding Guidelines
Function/Procedure Comments
The package header source file will document each function in the following format:
/*********************************************************************
/**
/** Function: get_employee_ssn
Confidential ©TopCoder Software, Inc. 2002 Page 2
/** In: p_employee_id – the id of the employee to search for
/** Returns: the Social Security Number for the employee
/**
/*********************************************************************
The package header source file will document each procedure in the following format:
/*********************************************************************
/**
/** Procedure: ins_employee
/** Out: p_employee_id – the id of the newly created employee.
/** In: p_ssn – the Social Security Number of the employee to
/** insert.
/** In: p_name – the name of the employee to insert.
/**
/********************************************************************* 23
PL/SQL Coding Guidelines

The possible parameter types are ‘In’, ‘Out’ and ‘InOut’. These comments will be used at a later
time by an automated comment generator (possibly RoboDoc) to generate HTML package
documentation.

24
PL/SQL Coding Guidelines
Maximum Line Length
No single line of code in a PL/SQL component will exceed 120 characters in length.

Indentation
Indentation will be 0 spaces for the outermost block and 3 spaces from the indentation level of
each enclosing block.

Alignment
Comma separated lists will be ‘stacked’ and aligned as shown below:
SELECT SUM(A)
,B
,C
FROM TABLE1
WHERE B = 5
GROUP BY B
,C

25
PL/SQL Coding Guidelines

Conditional Blocks

In a conditional, the ‘THEN’ keyword will be placed on the line below the ‘IF’ but aligned with it.
‘ELSEIF’ keywords will also be aligned with the ‘IF’.
Example:
IF l_total > lc_max
THEN
l_new_max := true;
ELSIF l_total = lc_max
THEN
l_new_max := false;
END IF;

26
PL/SQL Coding Guidelines
Reserved Words

SQL and PL/SQL reserved words (SELECT, INSERT, PACKAGE, FUNCTION, etc) will be
capitalized.
Confidential ©TopCoder Software, Inc. 2002 Page 3

Variable Names
Variable names will be all lower case, with individual words separated by an underscore. The
following standard prefixes will be used:

Prefix Usage Context


p_ Function and procedure parameters
l_ Function and procedure local variables
g_ Package global variables
lc_ Function and procedure local constants
gc_ Package global constants

27
PL/SQL Coding Guidelines
Variable Types

Row and Column Types


When there is a direct correlation between a variable and a table column, the %TYPE or
%ROWTYPE will be used.
Example:
DECLARE
l_wins team.wins%TYPE;

Subtypes
When there’s no direct correlation between a variable and table column variable restrictions will
not be hard-coded. The developer will use ‘SUBTYPE’ to standardize data types.
Example:
CREATE OR REPLACE PACKAGE team_data
SUBTYPE total_win_count_t IS INTEGER(10);

DECLARE
l_win_count team_data.total_win_count_t;

28
PL/SQL Coding Guidelines
Variable Initialization
Variables will only be initialized in the ‘DECLARE’ section when that initialization doesn’t require a
function call or complex logic. When the variable must be initialized via a function call or complex
logic, it will be done in the executable section of the procedure or function.

Function and Procedure Naming


Functions and procedures will be names using the following guidelines. Functions and
procedures that don’t fall into one of these usage contexts will be named descriptively at the
developer’s discretion.
Prefix Usage Context
ins_ Procedures whose primary purpose is to insert data
upd_ Procedures whose primary purpose is to update data
del_ Procedures whose primary purpose is to delete data
get_ Functions whose primary purpose is to retrieve data
chk_ Functions which return a Boolean value

29
PL/SQL Debugging
Before you Debug

1. In order to debug a sub program you should have DEBUG privileges.

30
PL/SQL Debugging
2. If you don't have the required DEBUG privileges, a SYSDBA role user has to assign them. Login as a SYSDBA
user.
3.Execute the grant commands and ACL(Access Control List) script shown as a SYSDBA user.

31
PL/SQL Debugging
4. Now login as hr user, who has a non-sysdba user role
5. Execute the SQL statement shown to check whether required privileges are granted to hr user.

32
PL/SQL Debugging
Debugging

1. Compile the procedure

2. Run the procedure by clicking on Run icon

3. Change the default values to 120 for EMP_ID

4. To see how debug works, you create a break point. Click the line number 7.

33
PL/SQL Debugging

34
PL/SQL Debugging
5. When a break point is created at line 7, the execution will break at line 7 and allows developer to monitor
the data held in different variables. Click the Debug icon.

6. Click OK to accept the same input values as before.

7. The debugger is running and has stopped at line 8. Click the Smart Data tab. The Smart Data tab holds the
values of variables in the PL/SQL block. These are currently set to NULL.

35
PL/SQL Debugging
8. You can see all the data manipulated in the procedure in the Data tab. You see that the current
values of l_salary and l_commission are NULL.

36
PL/SQL Debugging
9. Click the Step Over icon to move to the next statement in the procedure.

37
PL/SQL Debugging
10. Notice the values for l_salary and l_commission have changed to the existing values in the database, as the
execution of select statement is complete, you can see the values from the database are fetched into the
variables in the procedure.

38
PL/SQL Debugging
11. Click the Step Over icon again to move to the next statement.As the execution of the update statement
completes, you can see the new values of salary and commission in the Data tab.

39
PL/SQL Debugging
12. Notice that the debugger moved to the next statement in the procedure. You want to run the rest of the
procedure, click the Resume icon.

40
PL/SQL Debugging
13. Procedure execution and debugging is complete. In the next topic, you create a test repository so that you
can create and run a unit test.

41
SQL Profiling

42
SQL Profiling
What is a SQL profile?

A SQL profile is a set of auxiliary information specific to a SQL statement. Conceptually, a SQL
profile is to a SQL statement what statistics are to a table or index. The database can use the
auxiliary information to improve execution plans.

A SQL profile contains corrections for poor optimizer estimates discovered by the SQL Tuning
advisor. This information can improve optimizer cardinality and selectivity estimates, which in
turn leads the optimizer to select better plans.

The SQL profile does not contain information about individual execution plans. Rather, the
optimizer has the following sources of information when choosing plans:
• The environment, which contains the database configuration, bind variable values, optimizer
statistics, data set, etc.

• The supplemental statistics in the SQL profile


Therefore, SQL profiles just guide the optimizer to a better plan.

43
SQL Profiling
What is the main use case for SQL profiles?

Automatic Database Diagnostic Monitor (ADDM) proactively identifies high-load SQL


statements that are good candidates for SQL tuning. One of the recommendations can be to
invoke a SQL Tuning Advisor on the high load SQL statements that ADDM has identified.
Also, it is possible to invoke SQL Tuning Advisor manually for on-demand tuning of one or
more SQL statements. To tune multiple statements, one must create a SQL tuning set (STS). A
SQL tuning set is a database object that stores SQL statements along with their execution
context.

SQL Tuning Advisor can recommend a profile the following types of statements:
• DML statements (SELECT, INSERT with a SELECT clause, UPDATE, and DELETE)
• CREATE TABLE statements (only with the AS SELECT clause)
• MERGE statements (the update or insert operations)
If a profile is recommended it will be in a form of a finding that allows for the profile to be
implemented. Once implemented, the database creates the profile and stores it persistently in the
data dictionary. If a user issues a statement for which a profile has been built, then the query
optimizer uses both the environment and the SQL profile to build a well-tuned plan.

44
SQL Profiling
What is the difference between SQL profiles, stored outlines,
and SQL plan baselines?

To achieve SQL plan stability in earlier releases of Oracle Database stored outlines played a
major role. In Oracle Database 11g they are still supported, however will be deprecated in the
future releases in favor of SQL plan management. The goal of SQL plan baselines (that are
generated by the SQL plan management mechanism) is to preserve the performance of
corresponding SQL statements, regardless of changes in the database.
SQL Profiles, on the other hand, were introduced in Oracle Database 10g and were supposed to
guide the Optimizer to a better plan. They do not guarantee the same plan each time the
statement is parsed.Network Databases
It is the database that typically follows the network data model. Here, the representation of data is in the form
of nodes connected via links between them.

45
SQL Profiling
What are the benefits of SQL profiles?

• Unlike hints and stored outlines, profiles do not tie the optimizer to a specific plan or subplan.
Profiles fix incorrect estimates while giving the optimizer the flexibility to pick the best plan in
different situations.
• Unlike hints, no changes to application source code are necessary when using profiles.
• The use of SQL profiles by the database is transparent to the user.

46
SQL Profiling

What are enhancements to SQL profiles in Oracle Database 11g?

Automatic SQL Tuning

Test execution

Parallel query profile recommendation

47
Queries?

48
Thank you

You might also like