0% found this document useful (0 votes)
7 views17 pages

Co3 Session 17

The document provides an overview of PL/pgSQL procedures, including syntax for declaring variables, control structures, and examples of using SELECT INTO statements. It covers the creation and calling of stored procedures and functions, emphasizing their advantages in modularity and reusability. Additionally, it explains parameter modes for functions and includes code examples for better understanding.

Uploaded by

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

Co3 Session 17

The document provides an overview of PL/pgSQL procedures, including syntax for declaring variables, control structures, and examples of using SELECT INTO statements. It covers the creation and calling of stored procedures and functions, emphasizing their advantages in modularity and reusability. Additionally, it explains parameter modes for functions and includes code examples for better understanding.

Uploaded by

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

Department of CSE

COURSE NAME: DBMS


COURSE CODE: 23AD2102R
Topic:
PROCEDURES IN PL/pgSQL

Session-17

CREATED BY K. VICTOR BABU


PL/PGSQL BLOCK

[ <<label>> ] /* A block : may have an optional label.

[ declare

declarations ] /* Declaration section: declare all variables here to be used within the body
section.

begin /* body section: contains set of PL/pgSQL statements. Each statement end with ;

statements;
... /* Blocks can be nested. A
nested block is a block placed
inside the body of another
end [ label ]; block.

2
DECLARATIONS

Syntax: Declare /* constants


variable_name data_type [:= expression]; vat constant numeric :=
Declare /* variables 0.1;
film_count integer := 0; net_price numeric :=
20.5;
start_at constant time :=
Variable Initialization through select into statement:
now();
select count(*) into film_count from film; /* film_count will be set to count(*) value.

Showing the message using raise notice statement:


raise notice 'The number of films is %', film_count; /* Placeholder % will be replaced by
film_count variable value.

3
DECLARATIONS..

• Declaring a variable that has the same datatype as the rowtype.

row_variable table_name%ROWTYPE;
row_variable view_name%ROWTYPE;
• To access the individual field of the row variable, we can use the dot notation (.)

row_variable.field_name
We can use row type variables (%ROWTYPE) to hold a row of a result set returned by the select
into statement.
• PostgreSQL provides a “type” called the record that is like the row-type. It can hold only one row
of a result set. Unlike a row-type variable, a record variable does not have a predefined structure.
The structure of a record variable is determined when the select or for statement assigns an
actual row to it.
variable_name record;

4
CODE EXAMPLES OF ROWTYPE AND RECORD TYPE VARIABLES

/* This example shows the first name and last name of the actor id
do $$ 10.
do
declare $$
declare
selected_actor actor%rowtype;
rec record;
begin begin
for rec in select title, length from film where
-- select actor with id 10 length > 50
select * from actor into selected_actor where actor_id = 10; order by length
loop
-- show the number of actor raise notice '% (%)', rec.title,
rec.length; end loop;
raise notice 'The actor name is % %',
end;
selected_actor.first_name, $$

selected_actor.last_name;
end; $$

5
PL/pgSQL Select Into statement

SYNTAX: select select_list into variable_name from table_expression;


EXAMPLE: select count(*) into actor_count from actor;

Control structures: if
statement
PL/pgSQL provides you with three forms of the if statements.
•if then Syntax if then elif
•if then else if condition_1 then
•if then elsif statement_1;
Syntax if then elsif condition_2 then
if condition then statement_2
statements; ...
end if; elsif condition_n then
Syntax if then else
statement_n;
if condition then
else
statements;
else-statement;
else
end if;
alternative-statements;
end if;

6
CODE EXAMPLES

do $$ do $$
declare declare
selected_film film%rowtype; selected_film film%rowtype;
input_film_id film.film_id%type := 100; input_film_id film.film_id%type := 0;
begin begin
select * from film select * from film
into selected_film into selected_film
where film_id = input_film_id; where film_id = input_film_id;
if not found then if not found then
raise notice 'The film % could not be found', raise notice 'The film % could not be
input_film_id; found',
else input_film_id;
raise notice 'The film title is %', selected_film.title; end if;
end if; end $$
end $$
The found is a global variable that is available in PL/pgSQL procedure language.
The select into statement sets the found variable if a row is assigned or false if no row is returned.

7
CONTROL STRUCTURES: CASE
STATEMENT
If the case statement
The case statement has two forms: cannot find any
• Simple case statement match, it will execute
• Searched case statement the else section.
case statement selects a section to execute based on condition.
The else section is
Syntax of simple case statement: Syntax of Searched case
optional.
case search-expression statement:
when expression_1 [, expression_2, ...] then case
when-statements when boolean-expression-1
[ ... ] then
[else statements
else-statements ] [ when boolean-expression-2
END case; then
statements
... ]
[ else
statements ]
8 end case;
CODE EXAMPLES

do $$ else
declare price_segment = 'Unspecified';
rate film.rental_rate%type; end case;
price_segment varchar(50); raise notice '%', price_segment;
begin end if;
-- get the rental rate end; $$
select rental_rate into rate
from film
where film_id = 100;
-- assign the price segment
if found then
case rate
when 0.99 then
price_segment = 'Mass';
when 2.99 then
price_segment = 'Mainstream';
when 4.99 then
price_segment = 'High End';

9
CONTROL STRUCTURES: LOOPS
-- executes a block of code repeatedly based on a condition.
While loop Syntax: For loop Syntax:

[ <<label>> ]
[ <<label>> ]
for loop_counter in [ reverse ] from.. to [ by step ]
while condition loop
statements;
loop
end loop; statements
do $$ end loop [ label ];

While loop example: For loop example:


declare do $$
counter integer := 0;
begin
begin
while counter < 5 loop for counter in 1..5 loop
raise notice 'Counter %', counter; raise notice 'counter: %', counter;
counter := counter + 1; end loop;
end loop; end; $$
end$$;

10
LOOP USED TO ITERATE THE RESULTSET OF A QUERY: CODE EXAMPLE.

Use exit statement to terminate a loop or to exit a


do
block.
$$
declare Use the continue statement to skip the current
f record; loop iteration prematurely and start a new one.
begin
for f in select title, length
from film
order by length desc, title
limit 10
loop
raise notice '%(% mins)', f.title,
f.length;
end loop;
end;
$$

11
STORED PROCEDURES AND FUNCTIONS IN
PLPGSQL
•Procedures and functions are very similar to those found in most high-level
programming languages and have the same advantages:

•This reduces duplication of effort and improves software modularity and


extensibility.

•promote reusability and maintainability

•aid abstraction

•In databases, many applications can access the procedure stored on the server.
Server acts as a single point of change.

•Stored procedures and functions allow business logic to be stored in databases


which can be invoked from SQL statements.

12
CREATE AND CALL PROCEDURE IN PLPGSQL

Syntax of call procedure:


call stored_procedure_name(argument_list);
Syntax of create procedure:
create [or replace] procedure procedure_name(parameter_list)
language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end; $$ Syntax of drop procedure:
drop procedure [if exists] procedure_name
(argument_list)
[cascade | restrict]
13
CREATING A STORED PROCEDURE NAMED TRANSFER THAT TRANSFERS A SPECIFIED
AMOUNT OF MONEY FROM ONE ACCOUNT TO ANOTHER.

create or replace procedure transfer( -- adding the amount to the receiver's


sender int, account
receiver int, update accounts
amount dec set balance = balance + amount
) where id = receiver;
language plpgsql commit;
as $$ end;$$
begin
-- subtracting the amount from the sender's account
update accounts
set balance = balance - amount
where id = sender;

Calling transfer procedure:


Dropping transfer
call transfer(1,2,1000); procedure:
drop procedure transfer;

14
CREATE AND CALL FUNCTION IN PLPGSQL

• The create function statement allows you to define a new user-defined


function.
Syntax:
create [or replace] function
function_name(param_list)
returns return_type
language plpgsql
as
$$
declare
-- variable declaration
begin
-- logic
end;
$$
15
CREATING AND CALLING A FUNCTION

create function get_film_count(len_from int, len_to int)


returns int
language plpgsql
as
$$
declare
film_count integer; PostgreSQL provides three ways to call a user-defined
begin function:
select count(*) •Using positional notation
into film_count • select get_film_count(40,90);
from film •Using named notation
where length between len_from and len_to; select get_film_count(
return film_count; len_from => 40,
end; len_to => 90
$$; );
•Using the mixed notation.
select get_film_count(40, len_to => 90);

16
PL/PGSQL PARAMETER MODES AND CODE EXAMPLE

create or replace function


• IN : Pass a value to get_film_stat(
function out min_len int,
out max_len int,
• OUT: Return a value out avg_len numeric)
from a function language plpgsql
as $$
• INOUT: Pass a value to a begin
function and return an select min(length),
max(length),
updated value.
avg(length)::numeric(5,1)
into min_len, max_len, avg_len
from film;
Calling function in a PL/pgSQL Query Statement: select * from
end;$$
get_film_stat();

17

You might also like