0% found this document useful (0 votes)
23 views11 pages

PLSQL

The document provides a comprehensive overview of PL/SQL, detailing its advantages, features, and various programming constructs such as conditional statements, looping statements, functions, procedures, and cursors. It emphasizes the integration of SQL with procedural programming, enhancing performance, productivity, and security. Additionally, it covers error handling, predefined exceptions, and the use of views and triggers in PL/SQL.

Uploaded by

patilsarthak2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views11 pages

PLSQL

The document provides a comprehensive overview of PL/SQL, detailing its advantages, features, and various programming constructs such as conditional statements, looping statements, functions, procedures, and cursors. It emphasizes the integration of SQL with procedural programming, enhancing performance, productivity, and security. Additionally, it covers error handling, predefined exceptions, and the use of views and triggers in PL/SQL.

Uploaded by

patilsarthak2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

PL-SQL

Contents
1. Advantages of PL-SQL ....................................................................................................................................... 2
2. Understanding PLSQL ....................................................................................................................................... 3
3. Conditional statements in PLSQL .................................................................................................................. 3
4. Looping statements in PLSQL ......................................................................................................................... 4
5. Functions ............................................................................................................................................................... 4
6. Procedures ............................................................................................................................................................ 5
7. Cursors ................................................................................................................................................................... 5
8. Exception Handling ............................................................................................................................................ 7
9. Guidelines for Avoiding and Handling PLSQL Errors and Exceptions .............................................. 7
10. Advantages of PLSQL Exceptions .............................................................................................................. 8
11. Summary of predefined PLSQL Exceptions............................................................................................ 8
12. Views ................................................................................................................................................................... 8
13. Advantages and disadvantages of views ................................................................................................. 9
14. Comparison between Views and Tables .................................................................................................. 9
15. Triggers............................................................................................................................................................ 10
16. Benefits and components of a trigger..................................................................................................... 10

pg. 1 Prof. Hatim J Kanorwala - PLSQL


1. Advantages of PL-SQL
Ans

a. Tight Integration with SQL


a. PL/SQL lets you use all the SQL Data manipulation, cursor control and translation control commands,
as well as all the SQL functions, operators and pseudo columns.
b. This extensive SQL support lets you manipulate Oracle data flexibly and safely.
c. The PL/SQL language is tightly integrated with SQL. You do not have to translate between SQL and
PL/SQL datatypes, a NUMBER or VARCHAR2 column in the database is stored in a NUMBER or
VARCHAR2 variable in PL/SQL.
d. This integration saves you both learning time and processing time.
e. Special PL/SQL language features let you work with table columns and rows without specifying the
datatypes, saving on maintenance work when the table definition change
f. PL/SQL supports both static and dynamic SQL.
g. The syntax of static SQL statements is known at precompile time and the preparation of the static SQL
occurs before runtime, whereas the syntax of dynamic SQL statements is not known until runtime.
h. Dynamic SQL is a programming technique that makes your applications more flexible and versatile
b. Better Performance
a. Without PL/SQL, Oracle must process SQL statements one at a time. Programs that issue many SQL
statements require multiple calls to the database, resulting in significant network and performance
overhead.
b. PL/SQL stored procedures are compiled once and stored in executable form, so procedure calls are
efficient. Because stored procedures execute in the database server, a single call over the network
traffic and improves response times.
c. Stored procedures are cached and shared among users, which lowers memory requirements and
invocation overhead.
c. Higher Productivity
a. PL/SQL lets you write very compact code for manipulating data.
b. In the same way that scripting languages such as Perl can read, transform and write data from files
c. PL/SQL can query, transform, and update data in a database.
d. PLSQL saves time on design and debugging by offering a full range of software-engineering features,
such as exception handling, encapsulation, data hiding and object-oriented datatypes.
d. Full Portability
a. Applications written in PL/SQL can run on any operating system and platform where the oracle
database runs.
b. With PL/SQL, you can write portable program libraries and reuse them in different environments.
e. Tight Security
a. PL/SQL stored procedures move application code from the client to the server, where you can protect
it from tampering, hide the internal details, and restrict who has access.
f. Access to Pre-defined Packages
a. Oracle provides product-specific packages that define APIs you can call from PL/SQL to perform many
useful tasks.
b. These packages include DBMS_ALERT for using database triggers, DBMS_FILE for reading and writing
operating system (OS) text files, DBMS_HTTP for making hypertext transfer protocol (HTTP) callouts,
DBMS_OUTPUT for display output from PLSQL blocks and subprograms
g. Support for OOP
a. Object types are an ideal object-oriented modeling told, which you can use to reduce the cost and
time required to build complex applications.
b. Besides allowing you to create software components that are modular, maintainable, and reusable,
object types allow different team of programmers to develop software components concurrently
pg. 2 Prof. Hatim J Kanorwala - PLSQL
c. In addition, object types allow for realistic data modelling.
d. Complex real-world entities and relationships map directly into object types.
e. This direct mapping helps your programs better reflect the world they are typing to simulate.
h. Support for Developing Web Applications and Pages
a. You can use PL/SQL to develop Web applications and Server Pages (PSPs).

2. Understanding PLSQL
Ans

1. PL/SQL combines the data-manipulating power of SQL with the processing power of procedural languages.
2. You can control program flow with statements like IF and LOOP.
3. As with other procedural programming languages, you can declare variables, define procedures and functions
and trap runtime errors.
4. PL/SQL lets you break down complex problems into easily readable procedural code, and reuse this code across
multiple platforms/applications.
5. When a problem can be solved through plain SQL, you can issue SQL commands directly inside your PL/SQL
programs, without learning new API`s.
6. PLSQL data types correspond with SQL column types, making it easy to interchange PLSQL variable with data
inside a table.

3. Conditional statements in PLSQL


Ans

a. Decision making statements are those statements which are in charge of executing a statement out of multiple
given statements based on some condition.
b. The condition will return either true or false. Based on what the condition returns, the associated statement
is executed.
c. This can be logically implemented in PL/SQL block using decision making statements.
d. The decision-making statements in PL/SQL are of two types:
a. If Else statements
b. Case statement
e. IF Statement
a. The if statement, or the if...then statement can be used when there is only a single condition to be
tested.
b. If the result of the condition is TRUE then certain specified action will be performed otherwise if it is
FALSE then no action is taken and the control of program will just move out of the if code block.
f. IF..THEN..ELSE
a. Using this statement group we can specify two statements or two set of statements, dependent on a
condition such that when the condition is true then one set of statements is executed and if the
condition is false then the other set of statements is executed.
g. IF..THEN..ELSIF..ELSE
a. It is used to check multiple conditions. Sometimes it is required to test more than one condition in that
case if...then...else statement cannot be used.
b. For this purpose, if...then...elsif...else statement is suitable in which all the conditions are tested one
by one and whichever condition is found to be TRUE, that block of code is executed.
c. And if all the conditions result in FALSE then the else part is executed.

pg. 3 Prof. Hatim J Kanorwala - PLSQL


4. Looping statements in PLSQL
Ans

a. There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially:
b. The first statement in a function is executed first, followed by the second, and so on.
c. Programming languages provide various control structures that allow for more complicated execution paths.
d. A loop statement allows us to execute a statement or group of statements multiple times and following is the
general form of a loop statement in most of the programming languages
e. Types of PLSQL Loops
a. Basic Loop
i. PL/SQL exit loop is used when a set of statements is to be executed at least once before the
termination of the loop.
ii. There must be an EXIT condition specified in the loop, otherwise the loop will get into an
infinite number of iterations.
iii. After the occurrence of EXIT condition, the process exits the loop.
b. While Loop
i. PL/SQL while loop is used when a set of statements has to be executed as long as a condition
is true, the While loop is used.
ii. The condition is decided at the beginning of each iteration and continues until the condition
becomes false.
c. For Loop
i. PL/SQL for loop is used when when you want to execute a set of statements for a
predetermined number of times.
ii. The loop is iterated between the start and end integer values.
iii. The counter is always incremented by 1 and once the counter reaches the value of end integer,
the loop ends.
d. Cursor For Loop
i. Covered in Cursor Section

5. Functions
Ans

a. A function is a sub program that computes a value.


b. Functions and procedures are structured alike, except that functions have a RETURN value.
c. Functions have a number of optional keywords, used to declare a special class of functions known as table
functions.
d. They are typically used for transforming large amounts of data in data warehousing applications.
e. A function has two parts: the spec and the body.
f. The function spec begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the
datatype of the return value. Parameter declarations are optional.
g. Functions that take no parameters are written without parenthesis.
h. The function body begins with the keywords IS or AS and ends with the keyword end followed by an optional
function name.
i. The function body has three parts: a declarative part, an executable part, and an optional exception-handling
part.
j. The declarative part contains local declaration, which are placed between the keywords IS and begin.
k. The keyword DECLARE is not used. The executable part contains statements, which are placed between
keywords BEGIN and EXCEPTION (or END).
l. One or more RETURN statements must appear in the executable part of a function.

pg. 4 Prof. Hatim J Kanorwala - PLSQL


m. The exception handling part contains exception handlers, which are placed between the keywords EXCEPTION
and END;
n. The RETURN statement immediately ends the execution of a subprogram and returns the control to the caller.
o. Execution continues with the statement following the subprogram call.
p. In functions, a RETURN statement must contain an expression, which is evaluated when the RETURN statement
is executed.
q. The resulting value is assigned to the function identifier, which acts like a variable of the type specified in the
RETURN clause.

6. Procedures
Ans

a. A procedure is a subprogram that performs a specific action.


b. You specify name of the procedure, its parameters, its local variables, and the BEGIN-END block that contains
its code and handles any exceptions.
c. For each parameter, you specify:
a. Its name
b. Its parameter mode (IN, OUT, INOUT). If you omit the mode, the default in IN. The optional NOCOPY
keyword speeds up processing of large OUT or IN OUT parameters.
c. Its Datatype. You can specify only the type, not any length or precision constraints.
d. Optionally, its default value.
d. A Procedure has two parts: the spec and the body.
e. The Procedure spec begins with the keyword PROCEDURE and ends with the procedure name or a parameter
list, followed by the reserved word IS or AS. Parameter declaration is optional
f. The procedure body has three parts: a declarative part, an executable part, and an optional exception-handling
part.
g. The declarative part contains local declaration, which are placed between the keywords IS and begin.
h. The keyword DECLARE is used for anonymous PLSQL blocks, but not procedures.
i. The executable part contains statements, which are placed between keywords BEGIN and EXCEPTION (or END).
j. At least one statement must appear in the executable part of the procedure.
k. You can use the NULL statement to define a placeholder procedure or specify that the procedure does nothing.
l. The exception handling part contains exception handlers, which are placed between the keywords EXCEPTION
and END;
m. IN, OUT, IN OUT
a. Parameter modes that define the behavior of formal parameters.
b. An IN parameter passes values to the subprogram being called.
c. An OUT parameter returns values to the caller of the subprogram.
d. An IN OUT parameter lets passes initial value to the sub program being called and returns updated
values to the caller.

7. Cursors
Ans

a. PLSQL uses implicit and explicit cursors. PLSQL declares a cursor implicitly for all SQL data manipulation
statements, including queries that return only one row.
b. If you want precise control over query processing, you can declare an explicit cursor in the declarative part of
any PLSQL block, subprogram, or package.
c. You must declare an explicit cursor for queries that return more than one row.
d. Implicit cursors

pg. 5 Prof. Hatim J Kanorwala - PLSQL


a. Implicit cursors are managed automatically by PLSQL so you are not required to write any code to
handle these cursors.
b. However, you can track information about the execution of an implicit cursor through its cursor
attributes.
c. Implicit cursor attributes return information about the execution of DML and DDL statements.
d. The values of the cursor attributes always refer to the most recently executed SQL statement
e. The cursor attributes are:
i. %FOUND Attribute – Has a DML Statement Changed Rows?
1. Until a SQL data manipulation statement in executed, %FOUND yields NULL.
2. Thereafter, %FOUND yields TRUE if any INSERT, UPDATE, DELETE statement affected
one or more rows, or a SELECT INTO statement returned one or more rows. Otherwise,
%FOUND yields FALSE
ii. %ISOPEN Attribute – Always FALSE for Implicit cursors
1. Oracle closes the SQL cursor automatically after executing its associated SQL
statement.
2. As a result, %ISOPEN always yield FALSE
iii. %NOTFOUND Attribute – Has a DML Statement Failed to Change Rows?
1. %NOTFOUND is the logical opposite of %FOUND.
2. %NOTFOUND yields TRUE if an INSERT, UPDATE or DELETE statement affected no rows,
or a SELECT INTO statement returned no rows. Otherwise, %NOTFOUND yields FALSE
iv. %ROWCOUNT Attribute – How Many Rows Affected So Far?
1. %ROWCOUNT yields, the number of rows affected by and INSERT, UPDATE or DELETE
statement, or returned by a SELECT INTO statement.
2. %ROWCOUNT yields 0 if an INSERT, UPDATE or DELETE statement affected no rows, or
a SELECT INTO statement returned no rows.
f. Guideline for Implicit Cursor
i. The values of the cursor attribute always refer to the most recently executed SQL statement,
wherever that statement is.
ii. It might be in a different scope. To save an attribute value for later use, assign it to a local
variable immediately. Doing other operation, such as procedure calls, might change the value
of the variable before you can test it.
iii. The %NOTFOUND attribute is not useful in combination with SELECT INTO statement
1. If a SELECT INTO statement fails to return a row, PLSQL raises the predefined exception
NO_DATA_FOUND immediately, interrupting the flow of control before you can check
%NOTFOUND
2. A SELECT INTO statement that calls the statement, the %NOTFOUND attribute is
always FALSE, so checking it is unnecessary
e. Explicit Cursors
a. When you need precise control over query processing, you can explicitly declare a cursor in the
declarative part of any PLSQL block, subprogram or package
b. You use three commands to control a cursor: OPEN FETCH and CLOSE.
c. First, you initialize the cursor with the OPEN statement, which identifies the result set.
d. Then you can execute the FETCH repeatedly until all rows have been retrieved, or you can use the BULK
COLLECT clause to fetch all rows at once.
e. When the last row has been processed you release the cursor with the CLOSE statement.
f. This technique required more code than other techniques such as the implicit cursor FOR loop.
g. Its advantages are flexible. You can:
i. Process several queries in parallel by declaring and opening multiple cursors.
ii. Process multiple rows in a single loop iteration, skip rows, or split the processing into more
than one loop.
h. Attributes of Explicit Cursors:

pg. 6 Prof. Hatim J Kanorwala - PLSQL


i. Every explicit cursor and cursor variable has four attributes: %ISOPEN, %FOUND,
%NOTFOUND, %ROWCOUNT.
ii. When appended to the cursor or cursor variable name, these attributes return useful
information about the execution of SQL statement.
iii. You can use cursor attributes in procedural statements but not in SQL statements.

8. Exception Handling
Ans

a. In PLSQL, an error condition is called an exception.


b. Exceptions can be internally defined or user defined.
c. Examples of internally defined exceptions include division by zero and out of memory.
d. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The
other internal exceptions can be given names
e. You can define exceptions of your own in the declarative part of any PLSQL block, subprogram, or package.
f. For example, you might define an exception named insufficient_funds to flag overdrawn bank accounts. Unlike,
internal exceptions, user-defined exceptions must be given names.
g. When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the
exception-handling part of your PLSQL block or subprogram.
h. Internal exceptions are raised implicitly by the run time system
i. User-defined exceptions must be raised explicitly by RAISE statements, which can also raise predefined
exceptions
j. To handle raised exceptions, you write separate routines called exception handlers.
k. After an exception handler runs, the current block stops executing and the enclosing block resumes with the
next statement.
l. If there is no enclosing block, control returns to the host environment.

9. Guidelines for Avoiding and Handling PLSQL Errors and


Exceptions
Ans

a. Because reliability is crucial for database programs, use both error checking and exception handling to ensure
your program can handle all possibilities:
a. Add exception handlers whenever there is any possibility of an error occurring. Errors are especially
likely during arithmetic calculations, string manipulation, and database operations. Error could also
occur at other times.
b. Add error-checking code whenever you can predict that an error might occur if your code gets bad
input data. Except that at some time, your code will be passed incorrect or null parameters, that your
queries will return no rows or more rows than you except
c. Make your programs robust enough to work even if the database is not in the state you except.
d. Handle named exceptions whenever possible, instead of using WHEN OTHERS in exception handlers.
Learn the names and causes of the predefined exceptions. If your database operations might cause
particular ORA-errors, associate name with these errors so you can write handlers for them
e. Test your code with different combinations of bad data to see what potential errors arise
f. Write out debugging information in you exception handlers. You might store such information in a
separate table.
g. Carefully consider whether each exception handler should commit the transaction, roll it back, or let
it continue.

pg. 7 Prof. Hatim J Kanorwala - PLSQL


10. Advantages of PLSQL Exceptions
Ans

a. Using exceptions for error handling has several advantages. With exceptions, you can reliable handle potential
errors from many statements with a single exception handler.
b. Instead of checking for an error at every point it might occur, justa dd an exception handler to your PLSQL
block. If the exception is every raised in that block, you can be sure it will be handled.
c. Sometime the error is not immediately obvious, and could not be detected until later when you perform
calculations using bad data. Again, a single exception handler can trap all divison-by-zero errors, bad array
subscripts, and so on.
d. If you need to check for errors at the specific spot, you can enclose a single statement or a group of statements
inside its own BEGIN-END block with its own exception handler. You can make the checking as general or as
precise as you like
e. Isolating error-handling routines makes the rest of the program easier to read and understand.

11. Summary of predefined PLSQL Exceptions


Ans

a. An internal exception is raised automatically if your PLSQL program violates an Oracle rule or exceeds a system-
dependent limit.
b. PLSQL predefines some common Oracle errors as exception.
c. You can use the pragma EXCEPTION_INIT to associate exception names with other Oracle error codes that you
can anticipate.
d. To handle unexcepted Oracle errors, you can use the OTHER handler. Within this handler, you can call the
functions SQLCODE and SQLERRM to return the Oracle error code and message text.
e. Once you know the error code, you can use it with pragma EXCEPTION_INIT and write a handler specifically
for that error
f. PLSQL declares predefined exceptions globally in package STANDARD. You need not declare them yourself. You
can write handlers for predefined exception.

12. Views
Ans

a. A view is a virtual table in the database whose contents are defined via a query.
b. The views which has a set of named columns and rows of database data, appears to database users exactly like
an actual table.
c. When the data is queried, the rows and columns are visible to the view just way they are when a table is
searched.
d. The data of one or more tables are represented by views, which are also known as logical tables.
e. The base table on which a view is based, are where the view gets its data from
f. Any DML operations carried out on a view actually have an impact on the base table of the view i.e., any
insertion, updating or deletion done in a view will reflect in the base table
g. Views can be used in the same way as any other table
h. Types of views
a. Horizontal views
i. A horizontal view allows a user to only see the records of the deceased by horizontally slicing
the source database to produce the view

pg. 8 Prof. Hatim J Kanorwala - PLSQL


b. Vertical views
i. A vertical view restricts a user access to only certain columns of the table
c. Row/Column Subset View
i. Row/Column subset view is a combination of horizontal and vertical view which display few
selected rows satisfying the condition in the WHERE clause and few selected columns
d. Grouped View
i. A grouped view is one in which a query includes the GROUP BY clause, related rows of data
are grouped together and produce one row of result for each group
e. Joined View
i. One of the most frequent reasons for using views is to simplify multi-table queries.
ii. By specifying a two-table or three-table query in the view definition, you can create a joined
view that draws its data from two or three different tables and present the query results as a
single virtual table
iii. Once the view is defined, you can often use a simple, single table query against the view for
requests that would otherwise each require a two-table or three-table join.

13. Advantages and disadvantages of views


Ans

a. Advantages
a. Security
i. Each user can be given permission to access the database with the help of view that contain
specific data which is authorized to be accessed by the users.
b. Insulation from change
i. A view can present a consistent unchanged image of the database structure
c. Data Integrity
i. If data is accessed or entered to a view then the DBMS automatically ensures the integrity of
the database
d. Query simplicity
i. A view can be draw or certain data from different table and present it as a single table allowing
executing single table commands
b. Disadvantages
a. Performance
i. Performance is one of the disadvantages as if views created from multiple tables can slow
down the execution process
b. Update restriction
i. If view is created with the help of with check option then the updation in the view is restricted
against the where clause condition on the view is created

14. Comparison between Views and Tables


Ans

a. Views
a. This is one type of relation which is not a part of the physical database
b. It has no direct or physical relation with the database
c. Views can be used to provide security mechanism
d. Modifications through a view is not permitted
b. Table
a. A base relation is a relation that is not a derived relation
b. While it can manipulate the conceptual or physical relations stored in the data

pg. 9 Prof. Hatim J Kanorwala - PLSQL


c. It does not provide security
d. Modifications may be done with a base relation

15. Triggers
Ans

a. A trigger is a plsql block structure which is fired when a DML statements like INSERT, UPDATE and DELETE is
executed on a database table.
b. A trigger is triggered automatically when an associated DML statement in executed
c. Syntax for Creating a Trigger

CREATE [OR REPLACE] TRIGGER trigger_name

{BEFORE| AFTER} [INSERT [OR] | UPDATE [OR] | DELETE]

[ON table_name]

FOR EACH ROW

WHEN (conditions)

BEGIN

---sql statements

END;

d. CREATE [OR REPLACE] TRIGGER trigger_name: This clause creates a trigger with the given name or overwrites
an existing trigger with the same name
e. {BEFORE | AFTER}: This clause indicates at what time should the trigger gets fired. For example, Before or after
updating a table.
f. [INSERT [OR] | UPDATE [OR] | DELETE]: This clause determines the triggered event. More than one triggering
events can be used together separated by OR keyword. The trigger gets fired at all the specified triggered event
g. ON table_name: This clause identifies the name of the table or view to which the trigger is associated
h. FOR EACH ROW: this clause is used to determine whether a trigger must fire when each row gets affected or
just once when the entire statement is executed
i. WHEN (condition): This clause is valid only for row level triggers. This trigger is fired only for rows that satisfy
the condition specified.

16. Benefits and components of a trigger


Ans

a. Benefits
a. Generating some derived column values automatically
b. Enforcing referential integrity
c. Event logging and storing information on table access
d. Auditing
e. Synchronous replication of tables
f. Imposing security authorizations
g. Preventing invalid transactions
b. Components of trigger

pg. 10 Prof. Hatim J Kanorwala - PLSQL


a. Trigger SQL statements: The SQL statement on execution of which the defined trigger code file is called
Triggering SQL statement.
b. Trigger Action: The PLSQL block which gets executed when the triggering SQL statement is executed
c. Trigger Restriction: We can specify under what condition the trigger should be fire.

pg. 11 Prof. Hatim J Kanorwala - PLSQL

You might also like