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

Unit 1 (ADBC)

The document provides an overview of PL/SQL, a procedural language extension for SQL specifically designed for Oracle databases. It outlines the advantages, features, architecture, and fundamental concepts of PL/SQL, including variable declaration, control statements, and error handling. Additionally, it discusses the scope of variables and provides examples of using control structures like IF statements and loops.

Uploaded by

str86577
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)
3 views

Unit 1 (ADBC)

The document provides an overview of PL/SQL, a procedural language extension for SQL specifically designed for Oracle databases. It outlines the advantages, features, architecture, and fundamental concepts of PL/SQL, including variable declaration, control statements, and error handling. Additionally, it discusses the scope of variables and provides examples of using control structures like IF statements and loops.

Uploaded by

str86577
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/ 57

Advanced Database Concepts

SYCS SEM-3
Unit- 1
Overview of 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 is an embedded language. PL/SQL only can execute in an Oracle Database. It was not designed to use as a
standalone language like Java, C#, and C++.

In other words, you cannot develop a PL/SQL program that runs on a system that does not have an Oracle Database.
Advantages of PL/SQL

1. Enhancing database development – PL/SQL is a programming language specifically designed for


developing database applications, which can improve the efficiency and effectiveness of database
development.
2. Improving performance – PL/SQL can improve the performance of database applications by allowing
developers to create efficient and optimized code.
3. Providing error handling capabilities – PL/SQL includes built-in error handling capabilities, which can
help to ensure the reliability and stability of database applications.
4. Facilitating the creation of reusable code – PL/SQL allows developers to create reusable code, which
can save time and effort when developing new database applications.
5. Allowing for the integration of database and application logic – PL/SQL allows developers to integrate
database and application logic, which can improve the functionality and usability of database
applications.
Features

PL/SQL is tightly integrated with SQL.


It offers extensive error checking.
It offers numerous data types.
It offers a variety of programming structures.
It supports structured programming through functions and procedures.
It supports object-oriented programming.
It supports the development of web applications and server pages.
Architecture of PL/SQL:

PL/SQL Block PL/SQL Engine Database Server


Database Server

Declare
Declaration Statement;
SQL Lorem ipsum dolor sit amet, consectetur
SQL Statement
adipiscing elit, sed do eiusmod tempor. Ipsum

 executor
Begin
- From an expert dolor sit amet elit, sed do eiusmod tempor.
SQL statements; Procedural
Procedural statements;
statements
Exception
Exception handling
statement;
PL/SQL
END Statement
executor
PL/SQL Block PL/SQL Engine Database Server
Database Server

Declare
Declaration Statement;
SQL Lorem ipsum dolor sit amet, consectetur
SQL Statement
adipiscing elit, sed do eiusmod tempor. Ipsum

 executor
Begin
- From an expert dolor sit amet elit, sed do eiusmod tempor.
SQL statements; Procedural
Procedural statements;
statements
Exception
Exception handling
statement;
PL/SQL
END Statement
executor
PL/SQL Block PL/SQL Engine Database Server
Database Server

Declare
Declaration Statement;
SQL Lorem ipsum dolor sit amet, consectetur
SQL Statement
adipiscing elit, sed do eiusmod tempor. Ipsum

 executor
Begin
- From an expert dolor sit amet elit, sed do eiusmod tempor.
SQL statements; Procedural
Procedural statements;
statements
Exception
Exception handling
statement;
PL/SQL
END Statement
executor
PL/SQL Block PL/SQL Engine Database Server
Database Server

Declare
Declaration Statement;
SQL Lorem ipsum dolor sit amet, consectetur
SQL Statement
adipiscing elit, sed do eiusmod tempor. Ipsum

 executor
Begin
- From an expert dolor sit amet elit, sed do eiusmod tempor.
SQL statements; Procedural
Procedural statements;
statements
Exception
Exception handling
statement;
PL/SQL
END Statement
executor
Architecture of PL/SQL:

PL/SQL Block PL/SQL Engine Database Server


Database Server

Declare
Declaration Statement;
SQL Lorem ipsum dolor sit amet, consectetur
SQL Statement
adipiscing elit, sed do eiusmod tempor. Ipsum

 executor
Begin
- From an expert dolor sit amet elit, sed do eiusmod tempor.
SQL statements; Procedural
Procedural statements;
statements
Exception
Exception handling
statement;
PL/SQL
END Statement
executor
Fundamentals of PL/SQL
Like other programming languages, PL/SQL has a character set, reserved words, punctuation,
datatypes, and fixed syntax rules.

Character Sets and Lexical Units

PL/SQL programs are written as lines of text using a specif ic set of characters:

■ U p p e r - a n d l o w e r - c a s e l e t t e r s A . . Z a n d a . . z

■ N u m e r a l s 0 . . 9

■ S y m b o l s ( ) + – * / < > = ! ~ ^ ; : . ‘ @ % , ” # $ & _ | { } ? [ ]

■ Tabs, spaces, and carriage returns


A line of PL/SQL text contains groups of characters known as lexical units:

■ Delimiters (simple and compound symbols) – A delimiter is a simple or compound symbol that has a
special meaning to PL/SQL. For example, you use delimiters to represent arithmetic operations such as
addition and subtraction.

■ Identifiers(which include reserved words) – We use identifiers to name


PL/SQL program items and units, which include constants, variables, exceptions,
cursors, cursor variables, subprograms, and packages.

■ Literals – A literal is an explicit numeric, character, string, or BOOLEAN value


not represented by an identifier.

■ Comments – The PL/SQL compiler ignores comments, but you should not.
Adding comments to your program promotes readability and aids
understanding. Generally, you use comments to describe the purpose and use
of each code segment. PL/SQL supports two comment styles: single-line and
multi-line
Declarations

This section starts with the keyword DECLARE. It is an optional section and def in es all variables, cursors,
subprograms, and other elements to be used in the program.

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program.
It should have at least one executable line of code, which may be just a NULL
command to indicate that nothing should be executed.

Exception Handling

This section starts with the keyword EXCEPTION. This optional section contains
( )
What is Identifiers
Identifiers are nothing but a name that is given to a PL/SQL object. Each Identifier has some

special functions in pl Sql.

Properties of Identifiers

● Identifiers Must start with a letter

● Identifiers Maximum size is limited to 30 letters

● Identifiers Cannot contain whitespace characters

● Identifiers Can contain dollar sign (‘$’), underscore (‘_’) and hash sign (‘#’)

● Identifiers are case-insensitive


How to declare variable in PL/SQL
You must declare the PL/SQL variable in the declaration section or in a package as a global variable. After the
declaration, PL/SQL allocates memory for the variable's value and the storage location is identif ied by the variable
name.

Syntax for declaring variable:

1. variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Here, variable_name is a valid identif ier in PL/SQL and datatype must be valid PL/SQL data type. A data type with
size, scale or precision limit is called a constrained declaration. The constrained declaration needs less memory than
unconstrained declaration.

Example:

Radius Number := 5;

Date_of_birth date;
Naming rules for PL/SQL variables
The variable in PL/SQL must follow some naming rules like other programming languages.

○ The variable_name should not exceed 30 characters.

○ Variable name should not be the same as the table table's column of that block.

○ The name of the variable must begin with ASCII letter. The PL/SQL is not case sensitive so it could be either

lowercase or uppercase. For example: v_data and V_DATA refer to the same variables.

○ You should make your variable easy to read and understand, after the first character, it may be any number,

underscore (_) or dollar sign ($).

○ NOT NULL is an optional specification on the variable.


Data storing in Variables

● Once the variable is declared, they are ready to hold the data of defined type.

● The values of these variables can be assigned either in execution section or at the

time of declaring itself.

● The value can be either a literal or another variable’s value.

● Once a particular value has been assigned, it will be stored in the allocated memory

space for that variable.

● <variable_name> <datatype> : <default_value>


Declaration Restrictions:
In PL/SQL while declaring the variable some restrictions hold.

○ Forward references are not allowed i.e. you must declare a constant or variable before referencing it in

another statement even if it is a declarative statement.

val number := Total - 200;

Total number := 1000;

The first declaration is illegal because the TOTAL variable must be declared before using it in an

assignment expression.
○ Variables belonging to the same datatype cannot be declared in the same statement.

N1, N2, N3 Number;

It is an illegal declaration.
Example of initializing variable
Let's take a simple example to explain it well:

1. DECLARE
2. a integer := 30;
3. b integer := 40; After the execution, this will produce the following result:

4. c integer; Value of c: 70
5. f real;
Value of f: 33.333333333333333333
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
PL/SQL procedure successfully completed.
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;
Variable Scope in PL/SQL:
PL/SQL allows nesting of blocks. A program block can contain another inner block. If you declare a variable within an
inner block, it is not accessible to an outer block. There are two types of variable scope:

○ Local Variable: Local variables are the inner block variables which are not accessible to outer blocks.

○ Global Variable: Global variables are declared in outermost block.


Example of Local and Global variables
Let's take an example to show the usage of Local and Global variables in its simple form:

1. DECLARE
2. -- Global variables After the execution, this will produce the following result:
3. num1 number := 95;
4. num2 number := 85;
Outer Variable num1: 95

5. BEGIN
Outer Variable num2: 85
6. dbms_output.put_line('Outer Variable num1: ' || num1);
7. dbms_output.put_line('Outer Variable num2: ' || num2);
Inner Variable num1: 195
8. DECLARE
9. -- Local variables Inner Variable num2: 185
10. num1 number := 195;
11. num2 number := 185; PL/SQL procedure successfully completed.
12. BEGIN
13. dbms_output.put_line('Inner Variable num1: ' || num1);
14. dbms_output.put_line('Inner Variable num2: ' || num2);
15. END;
16. END;
17. /
control statements:

A control statement allows structured control of the sequence of application statements, such
as loops, and conditional tests. It also allows switching the input stream to another file, opening
and closing files, and various other operations.
IF-THEN Statement

● It is the simplest form of the IF control statement, frequently used in decision-making and
changing the control flow of the program execution.
● The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF.
● If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then
the IF statement does nothing.
Let us try an example that will help you understand the concept −
DECLARE
a number(2) := 10;
BEGIN a:= 10;
-- check the boolean condition using if statement
IF( a < 20 )
THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ‘ );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
IF-THEN-ELSE Statement

● A sequence of IF-THEN statements can be followed by an optional sequence of ELSE


statements, which execute when the condition is FALSE.
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 )
THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
IF-THEN-ELSIF statement
● The IF-THEN-ELSIF statement allows you to choose between several alternatives. An
IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The
ELSIF clause lets you add additional conditions.
● When using IF-THEN-ELSIF statements there are a few points to keep in mind.
• It's ELSIF, not ELSEIF.
• An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSIF's.
• An IF-THEN statement can have zero to many ELSIF's and they must come before
the ELSE.
• Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
CASE Statement

● Like the IF statement, the CASE statement selects one sequence of


statements to execute.
● However, to select the sequence, the CASE statement uses a selector
rather than multiple Boolean expressions.
● A selector is an expression, the value of which is used to select one of
several alternatives.
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Average');
when 'F' then dbms_output.put_line('Passed with Grace');
else dbms_output.put_line('Failed');
END CASE;
END;
PL/SQL Loop

● The PL/SQL loops are used to repeat the execution of one or more
statements for specif ie d number of times. These are also known as
iterative control statements.
PL/SQL While Loop
● 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.
● The condition is decided at the beginning of each iteration and continues
until the condition becomes false.
● Note: You must follow these steps while using PL/SQL WHILE Loop.
• Initialize a variable before the loop body.
• Increment the variable in the loop.
• You can use EXIT WHEN statements and EXIT statements in While loop but
it is not done often.
1. DECLARE
2. i INTEGER := 1;
3. BEGIN
4. WHILE i <= 10 LOOP
5. DBMS_OUTPUT.PUT_LINE(i);
6. i := i+1;
7. END LOOP;
8. END;
● /
1. DECLARE
2. VAR1 NUMBER;
3. VAR2 NUMBER;
4. BEGIN
5. VAR1:=200;
6. VAR2:=1;
7. WHILE (VAR2<=10)
8. LOOP
9. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
10. VAR2:=VAR2+1;
11. END LOOP;
12. END;
GOTO Statement

The GOTO statement allows you to transfer control to a labeled block or statement.
The following illustrates the syntax of the GOTO statement:
GOTO label_name;
The label_name is the name of a label that identifies the target statement. In the
program,
you surround the label name with double enclosing angle brackets as shown below:
<<label_name>>;
When PL/SQL encounters a GOTO statement, it transfers control to the first executable
statement after the label.
BEGIN
GOTO second_message;

<<first_message>>
DBMS_OUTPUT.PUT_LINE( 'Hello' );
GOTO the_end;

<<second_message>>
DBMS_OUTPUT.PUT_LINE( 'PL/SQL GOTO Demo' );
GOTO first_message;

<<the_end>>
DBMS_OUTPUT.PUT_LINE( 'and good bye...' );

END;
DECLARE
a number(2) := 30;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 50 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 35 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
Chapter 03 : Sequences
• A sequence is a user-def ined schema-bound object that generates a series
of numeric values.
• Sequences are frequently used in many databases because many
applications require each row in a table to contain a unique value and
sequences provide an easy way to generate them.
• The se que nce of nume ric value s is ge ne rate d in an asce nding or
descending order at def in ed intervals and can be conf igured to restart
when it exceeds max_value.
Different Features of Sequences
1. A sequence is a database object that generates and produces integer values in
sequential order.
2. It automatically generates the primary key and unique key values.
3. It may be in ascending or descending order.
4. It can be used for multiple tables.
5. Sequence numbers are stored and generated independently of tables.
6. It saves time by reducing application code.
7. It is used to generate unique integers.
8. It is used to create an auto number field.
9. Useful when you need to create a unique number to act as a primary key.
The syntax for creating a Sequence Object
is:

CREATE SEQUENCE schema_name.sequence_name


[INCREMENT BY interval]
[START WITH first_number]
[MAXVALUE max_value | NOMAXVALUE]
[MINVALUE min_value | NOMINVALUE]
[CYCLE | NOCYCLE]
[CACHE cache_size | NOCACHE]
[ORDER | NOORDER];
CREATE SEQUENCE

● Specify the name of the sequence after the CREATE SEQUENCE keywords.
If you want to create a sequence in a specific schema, you can specify the
schema name in along with the sequence name.
INCREMENT BY

● Specify the interval between sequence numbers after the INCREMENT BY keyword.

● The interval can have less than 28 digits. It also must be less than MAXVALUE -
MINVALUE.

● If the interval is positive, the sequence is ascending e.g., 1,2,3,…

● If the interval is negative, the sequence is descending e.g., -1, -2, -3 …

● The default value of interval is 1.


START WITH

● Specify the first number in the sequence.

● The default value of the first number is the minimum value of the sequence
for an ascending sequence and maximum value of the sequence for a
descending sequence.
MAXVALUE

● Specify the maximum value of the sequence.

● The max_value must be equal to or greater than first_number specify after


the START WITH keywords.
NOMAXVALUE

● Use NOMAXVALUE to denote a maximum value of 10^27 for an ascending


sequence or -1 for a descending sequence. Oracle uses this option as the
default.
● MINVALUE
● Specify the minimum value of the sequence.

● The min_value must be less than or equal to the first_number and must be
less than max_value.

● NOMINVALUE
● Use NOMINVALUE to indicate a minimum value of 1 for an ascending
sequence or -10^26 for a descending sequence. This is the default.
CYCLE

● Use CYCLE to allow the sequence to generate value after it reaches the
limit, min value for a descending sequence and max value for an ascending
sequence.

● When an ascending sequence reaches its maximum value, it generates the


minimum value.

● On the other hand, when a descending sequence reaches its minimum


value, it generates the maximum value.
NOCYCLE

● Use NOCYCLE if you want the sequence to stop generating the next value
when it reaches its limit. This is the default.
CACHE

● Specify the number of sequence values that Oracle will preallocate and
keep in the memory for faster access.
Example:

create sequence A2
start with 10
increment by 10
minvalue 10
maxvalue 50
cache 2
cycle;
PL/SQL Procedure
● The PL/SQL stored procedure or simply a procedure is a PL/SQL block
which performs one or more specific tasks. It is just like procedures in other
programming languages.
● The procedure contains a header and a body.
• He ade r: The he ade r contains the name of the proce dure and the
parameters or variables passed to the procedure.
• Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
How to pass parameters in procedure:
● When you want to create a procedure or function, you have to def in e
parameters .There is three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or
function. The value of the parameter cannot be overwritten by the
procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten by
the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten by
the procedure or function.
Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name


[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
● Create procedure example
● In this example, we are going to insert record in user table. So you need to create user
table first.
● Table creation:
1. create table user(id number(10) primary key,name varchar2(100));
● Now write the procedure code to insert record in user table.
● Procedure Code:
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
/
PL/SQL program to call procedure

● Let's see the code to call above created procedure.


BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy