SlideShare a Scribd company logo
1 of 7
Download to read offline
Motives for Using Stored Procedures
                                                                               Stored Procedures, UDFs and PL / pgSQL
                                                                               `                                                                            `
                                                                                       What are Stored procedures and what are they used for                        So far we implicitly assumed that we use a database from a
                                                                                                                                                                    client machine and issue SQL statements to a database
                                                                               `       What is a User Defined Function (UDF) and what is it used for
                                                                                       `   PostgreSQL syntax for UDFs
                                                                                                                                                            `       DBMS and the database itself reside on a different machine –
                                                                                       `   SQL UDFs
                                                                                                                                                                    database Server machine
                                                                               `       Procedural Language / PosgreSQL (PL/pgSQL)
                                                                                       `   Language Structure
                                                                                       `                                                                    `
                                                                                           Declarations                                                             There are a number of situations that make running small
                                                                                                                                                                    database procedures or functions on the server itself
                                                                                       `   Parameters and Types
                                                                                                                                                                    preferable
                                                                                       `   Special Statements
                                                    Basi di Dati                       `   Control Structures
                                                                               `       Triggers                                                             `       These small programs are historically known as database
                                                                                                                                                                    stored procedures
                                                          PL / pgSQL
                                                                               Reading:
                                                                                                                                                            `       SQL:1999 standard calls them persistent stored modules (PSM)
                                                                                           `   PostgreSQL 8.3 Documentation Chapter V.38

                                                                                                                                               PL / pgSQL                                                                      PL / pgSQL
                                                                                   3                                                                            4




Use Stored Procedures                                                          Declaring a Stored Procedure                                                 SQL/Persistent Stored Modules (PSM)
`       When:                                                                                                                                               `
                                                                               `                                                                                    SQL:1999 Standard introduces PSM
                                                                                       Commercial DBMS allow writing stored procedures
        `   Several applications need the same procedure,                              combining SQL and general purpose languages                          `       It is a programming language that contains:
        `   Data transfer should be reduced,
                                                                                                                                                                    `   Statements to create procedures and functions, and
        `   Tighter security control is needed,
                                                                                                                                                                    `   Procedural programming constructs for writing the body of a
                                                                               `       A stored procedure can be either a procedure or a
        `   More complex types of derived data should be made available
                                                                                                                                                                        procedure or a function
            to users,                                                                  function
                                                                                                                                                                    `   The body can also be a pure SQL statement
        `   Complex constraints, that cannot be specified by SQL
            declarative mechanisms, are needed                                                                                                              `       Procedural constructs include:
                                                                               `       It is stored as a database object and can be:
        `   Efficient execution of precompiled procedures is needed                                                                                                 `   Conditional IF/THEN/ELSE constructs, and
                                                                                       `   Used in SELECT statements, or                                            `   Several looping constructs:
`       Stored procedures allow for greater flexibility, if they are                   `   Called from within JDBC transaction programs, where a                        `   WHILE/DO/END WHILE
        changed all programs that call them remain intact                                  CollableStatement object has to be used                                      `   REPEAT/UNTIL/END REPEAT


                                                                  PL / pgSQL                                                                   PL / pgSQL                                                                      PL / pgSQL
    5                                                                              6                                                                            7
User Defined Functions                                                                The basic PostgreSQL UDF Syntax                                                 A Simple SQL Function
`                                                                                                                                                                     `
        A DBMS comes with many predefined functions                                                                                                                        A user defined function may be written using SQL
        `   Integer addition,
                                                                                                                                                                           CREATE FUNCTION poundtokg(float)
        `   String concatenation                                                                                                                                           RETURNS float
                                                                                    CREATE [ OR REPLACE ] FUNCTION                                                         AS ‘SELECT $1*0.545;’
`       An ORDBMS allows users to define new functions                                                                                                                     LANGUAGE ‘SQL’;
                                                                                              name ( [ [ argmode ] [ argname ] argtype [, ...] ] )
`       These functions are called server side functions since they                                                                                                        SELECT poundtokg(3.0);
                                                                                              [ RETURNS rettype ]
        reside at the database server                                               AS 'definition'
                                                                                                                                                                           poundtokg
`       Unlike client side functions, server side functions may be                  LANGUAGE langname                                                                      --------------------

        used from within SQL statements                                                                                                                                    1.635
                                                                                                                                                                           (1 row)
`       Each server side function may be called from any client
        side program
                                                                                                                                                                      `    $1 is a positional parameter


                                                                       PL / pgSQL                                                                        PL / pgSQL                                                                     PL / pgSQL
    8                                                                                     9                                                                               10




What is PL/pgSQL                                                                      Advantages of using PL/pg SQL                                                   Supported Data Types
                                                                                      `       Conventional queries:
`                                                                                                                                                                     `
        PL/pgSQL is a language that combines:                                                                                                                              PL/pgSQL functions accept as arguments and can return
                                                                                              `   Each SQL statement is submitted from a client to the database            as results any of the following data types:
        `   The expressive power of SQL with
                                                                                                  server for execution
                                                                                                                                                                           `   Scalar (base and user defined),
        `   The more typical features of a procedural programming
                                                                                              `   The server returns each result to the client
            language:                                                                                                                                                      `   Array,
                                                                                              `   This incurs inter process communication and may incur
            `   Control structures                                                                                                                                         `   Composite (row type),
                                                                                                  network overhead
            `   Complex computation
                                                                                                                                                                           `   Record (a placeholder whose structure is defined by the calling
                                                                                      `       User defined functions written in PL/pgSQL:
            `   Exception handling                                                                                                                                             query)
                                                                                              `   Reside on database server
`       It is aimed for:                                                                                                                                                   `   Polymorphic types (anyelement or anyarray),
                                                                                              `   Compile once per duration of a database connection
        `   Creating user defined functions                                                                                                                                `   Set,
                                                                                              `   Can comprise several SQL queries connected by procedural
        `   Creating trigger procedures                                                           constructs                                                               `   Void (no useful return value), and
                                                                                              `
        `                                                                                         All SQL queries of a function are executed with no
            Efficient execution (vaguely speaking it is precompiled)                                                                                                       `   Null
                                                                                                  intermediate client/server communication
        `   Easy of use
                                                                       PL / pgSQL                                                                        PL / pgSQL                                                                     PL / pgSQL
    11                                                                                    12                                                                              13
Record Type                                                             Body of a PL/pgSQL Function                                          Language Structure
                                                                                                                                             `    PL/pgSQL is a block structured language
`    Variables of the record type have no predefined
                                                                                                                                                  `   Each block starts with either a DECLARE, or BEGIN statement
                                                                             CREATE OR REPLACE FUNCTION some_func()
     structure                                                                                                                                    `   Ends with an END; statement
                                                                             RETURNS <data_type> AS
`    They take on the actual row structure of the row they are                                                                                    `   Each block can contain another block (also called subblock)
     assigned to during a SELECT command
                                                                                                                                                         BEGIN
                                                                             $$ --start of the body
`    The structure of a record variable can change each time                                                                                                     statements
                                                                             -- here comes the function body
     it is assigned to                                                                                                                                           BEGIN
                                                                             [DECLARE declarations]                                                                    statemnets
`    The record type is not a true type, only a record                                                                                                           END;
                                                                             BEGIN --denotes start of block statements
     placeholder                                                                                                                                         END;
                                                                             END;--denotes the end of a block
                                                                             $$ --end of the body
                                                                                                                                             `    BEGIN/END statements do not denote the start and the end
                                                                                                                                                  of a transaction, but only the boundaries of a block
                                                                             LANGUAGE ‘plpgsql’;
                                                           PL / pgSQL                                                           PL / pgSQL                                                                     PL / pgSQL
    14                                                                      15                                                                   16




Declarations                                                            Function Parameters (1)                                              Function Parameters (2)
                                                                        `    There are two ways to define function parameters                `
`                                                                                                                                                 The other way to define function parameters is
     All variables in a block must be declared in the
                                                                        `    One is to define their types only
     declaration section of the block (the only exception is the
                                                                                                                                                  CREATE FUNCTION area(a int, b int)
     variable of the for loop, which is an integer by
                                                                             CREATE FUNCTION area(int, int)                                       RETURNS int
     default)
                                                                             RETURNS int                                                          AS $$
`    Examples:                                                               AS $$                                                                   BEGIN
     `                                                                          BEGIN
         StudenName varchar;--initialized to null
                                                                                                                                                          RETURN a*b;
                                                                                     RETURN $1*$2;
     `   NumOfMarks real := 100.00; --assignment                                                                                                     END;
                                                                                END;
     `   Grade char(2) DEFAULT 'A+';                                                                                                              $$ LANGUAGE 'plpgsql';
                                                                             $$ LANGUAGE 'plpgsql';

                                                                                                                                             `
                                                                        `                                                                         Here, a contains the value of the first parameter, and b
                                                                             Here, $1 contains the value of the first parameter, and
                                                                             $2 contains the value of the second parameter                        contains the value of the second parameter
                                                           PL / pgSQL                                                           PL / pgSQL                                                                     PL / pgSQL
    17                                                                      18                                                                   19
Functions in SQL Queries With Tables                                             Functions in SQL Queries With Tables
RETURN Statement
`    To return single valued data from a function we use:                       `    A powerful use of functions is in queries that retrieve data                  CREATE OR REPLACE FUNCTION
                                                                                     from tables
                     RETURN expression                                                                                                                             area(real, real) RETURNS real
     statement                                                                                                                                                     AS 'SELECT $1*$2;' LANGUAGE 'SQL';
                                                                                     CREATE TABLE Rectangle (RectId int, a real, b real);
`    The RETURN statement with expression terminates
                                                                                     INSERT INTO Rectangle VALUES(1, 5.5, 6.6);
     the function and returns the value of the expression
                                                                                                                                                                   SELECT RectId, area(a, b) as Rec_Area
     to the caller                                                                   INSERT INTO Rectangle VALUES(2, 3.3, 4.4);
                                                                                                                                                                   FROM Rectangle;
`    The return value of a function must be defined:
     `   If control reaches the end of the top level block without hitting
                                                                                                RectId               a                  b
         a RETURN statement, a run time error will occur
                                                                                                                                                                                 RectId       Rec_Area
     `                                                                                             1                5.5                6.6
         Even if the function’s return value is declared to be void, a
                                                                                                                                                                                   1            36.3
         RETURN statement must still be provided (but will return                                  2                3.3                4.4
         nothing)                                                                                                                                                                  2           14.52


                                                                   PL / pgSQL                                                                       PL / pgSQL                                                   PL / pgSQL
    20                                                                              21                                                                            22




                                                                                                                                                                 Example 1
SELECT . . . INTO (1)                                                           SELECT . . .INTO (2)
                                                                                `    If a SELECT command returns no rows, null values are
`    The result of a SELECT command yielding multiple                                assigned to the target                                                      DECLARE
     columns (but only one row) can be assigned to a record                                                                                                        s record;
     variable                                                                   `    If a SELECT command returns multiple rows only one of the                   BEGIN
                                                                                     them, the first one retrieved is assigned to the target,                      SELECT * INTO s FROM student
                                                                                                                                                                   WHERE studentid=4;
     SELECT <attrbute_list> INTO <target>                                                                                                                          IF s.StudentId IS NULL THEN
                                                                                     DECLARE
                                                                                         s record; --s is the target                                                    RAISE NOTICE 'There is no student with id = 4';
     FROM…                                                                           BEGIN                                                                              RETURN NULL;
                                                                                         SELECT * INTO s FROM Student;                                             ELSE
                                                                                         RETURN s;                                                                      RETURN s;
`    If the target type is record, it automatically                                  END;                                                                          END IF;
     configures to the query result                                                                                                                              END;
                                                                                `    If the table is empty, s will be (, , , ) – a structure with null
                                                                                     components


                                                                   PL / pgSQL                                                                       PL / pgSQL                                                   PL / pgSQL
    23                                                                              24                                                                            25
Example 2                                                                   Obtaining the Result Status (FOUND)                                             An Example for the FOUND Variable
                                                                            `    To determine the result of a command, you can check a
DECLARE                                                                                                                                                     DECLARE
                                                                                 special variable named FOUND of the type boolean
  t record;                                                                                                                                                   t record;
BEGIN                                                                                                                                                       BEGIN
  IF p < 0 THEN --p is a variable                                                                                                                                 SELECT * INTO t FROM Grades
                                                                            `    The following commands set FOUND:
       SELECT * INTO t FROM Student                                                                                                                               WHERE StudentId = 007 AND CourseId= 'COMP302';
                                                                                 `   SELECT...INTO... sets it true if it returns any row, false
       WHERE StudentId = 007;                                                                                                                                     IF NOT FOUND THEN
                                                                                     otherwise
  ELSE                                                                                                                                                                  SELECT * INTO t FROM Student
                                                                                 `   PERFORM sets it true if it returns (and discards) any row, false
       SELECT * INTO t FROM Grades                                                                                                                                      WHERE StudentId = 007;
                                                                                     otherwise
       WHERE StudentId = 007 AND CourseId ='COMP302';                                                                                                             END IF;
  END IF;                                                                                                                                                         RETURN t;
                                                                                 `   UPDATE, INSERT, and DELETE set it true if at least one
  return t;                                                                                                                                                 END;
                                                                                     row is affected, false otherwise
END;

                                                                            `    FOUND is a local variable within each PL/pgSQL function

                                                               PL / pgSQL                                                                      PL / pgSQL                                                           PL / pgSQL
    26                                                                          27                                                                              28




                                                                                                                                                            Control Statements
RAISE Statement                                                             A RAISE NOTICE Example
                                                                                                                                                            `    PL/pgSQL supports different forms of IF conditional:
                                                                                 DECLARE
`    Even though PL/pgSQL doesn’t offer a way to intercept
                                                                                                                                                                 `   From:
     errors, the RAISE statement is provided to raise an error                      s record;
                                                                                                                                                                     `   IF. . .THEN. . .END IF;
                                                                                 BEGIN
                                                                                                                                                                 `   To:
                                                                                    SELECT * INTO s FROM Student;
`    Syntax:                                                                                                                                                         `   IF. . .THEN. . .ELSEIF. . .THEN. . .ELSE. . .
                                                                                    IF NOT FOUND THEN                                                                    END IF;
     RAISE severity 'message' [, variable []];
                                                                                                                                                            `    Also, PL/pgSQL supports the following looping statements:
                                                                                         RAISE NOTICE 'Table is empty';
     where severity can be:
                                                                                                                                                                 `   LOOP,
                                                                                         RETURN null;
     `   DEBUG
                                                                                                                                                                 `   EXIT,
                                                                                    ELSE
     `   NOTICE – just to send a message to the client application
                                                                                                                                                                 `   WHILE, and
                                                                                         RETURN s;
     `   EXCEPTION – to raise an exception, which is handled as                                                                                                  `   FOR
                                                                                    END IF;
         described in the manual
                                                                                                                                                                 `   Have a look in the manual for particulars
                                                                                 END;

                                                               PL / pgSQL                                                                      PL / pgSQL                                                           PL / pgSQL
    29                                                                          30                                                                              31
Next topic                                                                 The Trigger Syntax                                                                Trigger Procedures in PL/pg SQL
`                                                                                                                                                            `
     Triggers                                                                                                                                                     A trigger procedure is created with
                                                                                    <trigger>::= CREATE TRIGGER <trigger_name>
                                                                                                                                                                                   CREATE FUNCTION
                                                                                    {AFTER | BEFORE} <triggering_event> [OR...]
                                                                                                                                                                  command, which:
                                                                                    ON <table_name>
                                                                                                                                                                  `   Does not have any parameters, and
                                                                                    [FOR [EACH] { ROW | STATEMENT }]
                                                                                                                                                                  `   Has a trigger return type
                                                                                    EXECUTE PROCEDURE <function_name>(arguments);


                                                                                    <triggering_events>::=
                                                                                                                                                             `    When a PL/pgSQL function is called as a trigger, several
                                                                                       <triggerng_event> [OR <triggering_event>…..]
                                                                                                                                                                  special variables are created automatically in the top level
                                                                                                                                                                  block
                                                                                    <triggering_event>::= {INSERT | DELETE | UPDATE}



                                                              PL / pgSQL                                                                        PL / pgSQL                                                                     PL / pgSQL
    32                                                                         33                                                                                34




Automatically Created Variables                                            RETURN Type                                                                       Returning a Value Being Not NULL
                                                                                                                                                             `    A row level trigger fired BEFORE may return NULL to
`                                                                          `
     The most important automatically created variables:                        A trigger has to return:
                                                                                                                                                                  signal the trigger manager to skip the rest of operations
                                                                                `    Either NULL, or
     `   NEW of data type RECORD holding the new database row for
                                                                                                                                                                  for this row (the INSERT/DELETE/UPDATE will not be
                                                                                `    A record/row value having exactly the structure of the table
         INSERT/UPDATE operations in row level triggers
                                                                                                                                                                  executed for this row)
                                                                                     the trigger was fired for
     `   OLD of data type RECORD holding the old database row for
         UPDATE/DELETE operations in row level triggers
                                                                                                                                                             `    If a BEFORE row level trigger returns a non null value,
                                                                           `    The return value of a:                                                            the operation proceeds with that row value:
                                                                                `    BEFORE or AFTER per statement trigger, or
`    There are also other variables generated (have a look in                                                                                                     `   Returning a row value different from the original value of NEW
                                                                                `                                                                                     alters the row that will be inserted or updated (but has no
                                                                                     An AFTER row level trigger is always ignored
     the PostgreSQL Manual)
                                                                                                                                                                      influence on delete operation)
                                                                                `    Both should be NULL
                                                                                                                                                                  `   Altering a row to be stored is accomplished either by replacing
                                                                                `    But they can still abort an entire operation by raising en error
                                                                                                                                                                      single values directly in NEW, or building a completely new
                                                                                                                                                                      record/row

                                                              PL / pgSQL                                                                        PL / pgSQL                                                                     PL / pgSQL
    35                                                                         36                                                                                37
Triggers Examples                                                                                                                                                  Summary (1)
                                                                               Referential Integrity Trigger INSERT
`                                                                                                                                                                  `
     Consider the following part of a relational database                                                                                                               Stored Procedures have a widespread use in industry
                                                                                    CREATE TRIGGER ins_ref_int
     schema:                                                                                                                                                            since they allow for:
                                                                                    BEFORE INSERT ON Exam FOR EACH ROW
                                                                                    EXECUTE PROCEDURE ins_ref_int();
                                                                                                                                                                        `   Code sharing,
                                                                                                                                                                        `
                                                                                    CREATE OR REPLACE FUNCTION ins_ref_int()                                                Tighter security control,
     Student (StudId, Name, NoOfPts, Degree)                                        RETURNS trigger AS $$
                                                                                                                                                                        `   Efficient execution
                                                                                    DECLARE s RECORD;
     Exam (StudId, CourseId, Term, Grade)                                           BEGIN
                                                                                                                                                                   `    User Defined Functions (UDFs):
                                                                                      SELECT * INTO s FROM Student WHERE NEW.StudId = StudId;
                                                                                                                                                                        `
                                                                                      IF NOT FOUND THEN                                                                     Can be defined using SQL only, or a combination of SQL and a
`    Suppose DBMS does not support referential integrity                                 RAISE NOTICE 'There is no student %', NEW.StudId;
                                                                                                                                                                            procedural language
                                                                                         RETURN NULL;
     constraints                                                                                                                                                        `
                                                                                      ELSE                                                                                  Can be used as stored procedures,
                                                                                         RETURN NEW;
                                                                                                                                                                        `   Can be used as trigger procedures
                                                                                      END IF;
                                                                                    END;
                                                                                    $$ LANGUAGE 'PLpgSQL';


                                                                  PL / pgSQL                                                                          PL / pgSQL                                                                   PL / pgSQL
    38                                                                             39                                                                                  40




Summary (2)                                                                    Summary (3)
                                                                               `    PL/pgSQL is a simple language that combines procedural constructs with
`    Triggers are active rules that are automatically fired when
                                                                                    SQL statements
     an event occurs
                                                                               `    It is designed to provide for:
     `   In the PostgreSQL environment triggers use PL/pgSQL                        `   Creating user defined functions
         procedures                                                                 `   Creating trigger procedures
     `   Triggers are extensively used to implement constraints                     `   Efficient execution (vaguely speaking it is precompiled)
                                                                                    `   Easy to use
                                                                               `    It is block structured
                                                                               `    Supports
                                                                                    `   A waste range of data types
                                                                                    `   Conditionals
                                                                                    `   Looping
                                                                                    `   Special statements (SELECT INTO)


                                                                  PL / pgSQL                                                                          PL / pgSQL
    41                                                                             42

More Related Content

Viewers also liked (17)

Basi Dati c4
Basi Dati c4Basi Dati c4
Basi Dati c4
 
Basi Dati F1
Basi Dati F1Basi Dati F1
Basi Dati F1
 
Basi Dati B6
Basi Dati B6Basi Dati B6
Basi Dati B6
 
Basi Dati B1
Basi Dati B1Basi Dati B1
Basi Dati B1
 
Calc Num Es 13.05.09
Calc Num Es 13.05.09Calc Num Es 13.05.09
Calc Num Es 13.05.09
 
Basi Dati E6
Basi Dati E6Basi Dati E6
Basi Dati E6
 
Basi Dati C6
Basi Dati C6Basi Dati C6
Basi Dati C6
 
Calc Num Zanni 01
Calc Num Zanni 01Calc Num Zanni 01
Calc Num Zanni 01
 
Basi Dati E4
Basi Dati E4Basi Dati E4
Basi Dati E4
 
Basi Dati E2
Basi Dati E2Basi Dati E2
Basi Dati E2
 
Info Industr Riass Standard
Info Industr Riass StandardInfo Industr Riass Standard
Info Industr Riass Standard
 
Basi Dati d3
Basi Dati d3Basi Dati d3
Basi Dati d3
 
Basi Dati C3
Basi Dati C3Basi Dati C3
Basi Dati C3
 
Calc Num Prato 02
Calc Num Prato 02Calc Num Prato 02
Calc Num Prato 02
 
Basi Dati B3
Basi Dati B3Basi Dati B3
Basi Dati B3
 
Basi Dati d1
Basi Dati d1Basi Dati d1
Basi Dati d1
 
Calc Num Prato 01(21.05.09)
Calc Num Prato 01(21.05.09)Calc Num Prato 01(21.05.09)
Calc Num Prato 01(21.05.09)
 

Similar to Basi Dati F1 Bis

02 -my_sql_roma-may2011
02  -my_sql_roma-may201102  -my_sql_roma-may2011
02 -my_sql_roma-may2011
testfank
 
OOW09 Ebs Tuning Final
OOW09 Ebs Tuning FinalOOW09 Ebs Tuning Final
OOW09 Ebs Tuning Final
jucaab
 
The Art & Sience of Optimization
The Art & Sience of OptimizationThe Art & Sience of Optimization
The Art & Sience of Optimization
Hertzel Karbasi
 
Jfokus 2012: PaaSing a Java EE Application
Jfokus 2012: PaaSing a Java EE ApplicationJfokus 2012: PaaSing a Java EE Application
Jfokus 2012: PaaSing a Java EE Application
Arun Gupta
 
D17316 gc20 l03_broker_em
D17316 gc20 l03_broker_emD17316 gc20 l03_broker_em
D17316 gc20 l03_broker_em
Moeen_uddin
 
exadata-database-machine-kpis-3224944.pdf
exadata-database-machine-kpis-3224944.pdfexadata-database-machine-kpis-3224944.pdf
exadata-database-machine-kpis-3224944.pdf
TricantinoLopezPerez
 

Similar to Basi Dati F1 Bis (20)

MySQL Performance Schema in Action
MySQL Performance Schema in Action MySQL Performance Schema in Action
MySQL Performance Schema in Action
 
Parallel processing in data warehousing and big data
Parallel processing in data warehousing and big dataParallel processing in data warehousing and big data
Parallel processing in data warehousing and big data
 
Sqlmr
SqlmrSqlmr
Sqlmr
 
Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)
 
Sqlmr
SqlmrSqlmr
Sqlmr
 
Sqlmr
SqlmrSqlmr
Sqlmr
 
Sqlmr
SqlmrSqlmr
Sqlmr
 
02 -my_sql_roma-may2011
02  -my_sql_roma-may201102  -my_sql_roma-may2011
02 -my_sql_roma-may2011
 
Running deep neural nets in your Java application with Deeplearning4j
Running deep neural nets in your Java application with Deeplearning4jRunning deep neural nets in your Java application with Deeplearning4j
Running deep neural nets in your Java application with Deeplearning4j
 
No sql
No sqlNo sql
No sql
 
Whatsnew in-my sql-primary
Whatsnew in-my sql-primaryWhatsnew in-my sql-primary
Whatsnew in-my sql-primary
 
Oracle architecture
Oracle architectureOracle architecture
Oracle architecture
 
Collaborate 2012 - RMAN eliminate the mystery
Collaborate 2012 - RMAN eliminate the mysteryCollaborate 2012 - RMAN eliminate the mystery
Collaborate 2012 - RMAN eliminate the mystery
 
OOW09 Ebs Tuning Final
OOW09 Ebs Tuning FinalOOW09 Ebs Tuning Final
OOW09 Ebs Tuning Final
 
Collaborate 2012 - Administering MySQL for Oracle DBAs
Collaborate 2012 - Administering MySQL for Oracle DBAsCollaborate 2012 - Administering MySQL for Oracle DBAs
Collaborate 2012 - Administering MySQL for Oracle DBAs
 
The Art & Sience of Optimization
The Art & Sience of OptimizationThe Art & Sience of Optimization
The Art & Sience of Optimization
 
Jfokus 2012: PaaSing a Java EE Application
Jfokus 2012: PaaSing a Java EE ApplicationJfokus 2012: PaaSing a Java EE Application
Jfokus 2012: PaaSing a Java EE Application
 
D17316 gc20 l03_broker_em
D17316 gc20 l03_broker_emD17316 gc20 l03_broker_em
D17316 gc20 l03_broker_em
 
EQUNIX - PPT 11DB-Postgres™.pdf
EQUNIX - PPT 11DB-Postgres™.pdfEQUNIX - PPT 11DB-Postgres™.pdf
EQUNIX - PPT 11DB-Postgres™.pdf
 
exadata-database-machine-kpis-3224944.pdf
exadata-database-machine-kpis-3224944.pdfexadata-database-machine-kpis-3224944.pdf
exadata-database-machine-kpis-3224944.pdf
 

More from Bombers Falcoman (18)

Calc Num Prato 04
Calc Num Prato 04Calc Num Prato 04
Calc Num Prato 04
 
Calc Num Prato 03
Calc Num Prato 03Calc Num Prato 03
Calc Num Prato 03
 
Basi Dati F2
Basi Dati F2Basi Dati F2
Basi Dati F2
 
Basi Dati F1 Es
Basi Dati F1 EsBasi Dati F1 Es
Basi Dati F1 Es
 
Basi Dati E5
Basi Dati E5Basi Dati E5
Basi Dati E5
 
Basi Dati E3
Basi Dati E3Basi Dati E3
Basi Dati E3
 
Basi Dati E1
Basi Dati E1Basi Dati E1
Basi Dati E1
 
Basi Dati C7
Basi Dati C7Basi Dati C7
Basi Dati C7
 
Basi Dati C Riepilogo
Basi Dati C RiepilogoBasi Dati C Riepilogo
Basi Dati C Riepilogo
 
Basi Dati C5 Es
Basi Dati C5 EsBasi Dati C5 Es
Basi Dati C5 Es
 
Basi Dati C6 Es
Basi Dati C6 EsBasi Dati C6 Es
Basi Dati C6 Es
 
Basi Dati C5
Basi Dati C5Basi Dati C5
Basi Dati C5
 
Basi Dati d4
Basi Dati d4Basi Dati d4
Basi Dati d4
 
Basi Dati d2
Basi Dati d2Basi Dati d2
Basi Dati d2
 
Basi Dati c4 es
Basi Dati c4 esBasi Dati c4 es
Basi Dati c4 es
 
Info Industr Conc Generali Plc
Info Industr Conc Generali PlcInfo Industr Conc Generali Plc
Info Industr Conc Generali Plc
 
Appunti Info Indust
Appunti Info IndustAppunti Info Indust
Appunti Info Indust
 
Basi Dati C3 es
Basi Dati C3 esBasi Dati C3 es
Basi Dati C3 es
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Basi Dati F1 Bis

  • 1. Motives for Using Stored Procedures Stored Procedures, UDFs and PL / pgSQL ` ` What are Stored procedures and what are they used for So far we implicitly assumed that we use a database from a client machine and issue SQL statements to a database ` What is a User Defined Function (UDF) and what is it used for ` PostgreSQL syntax for UDFs ` DBMS and the database itself reside on a different machine – ` SQL UDFs database Server machine ` Procedural Language / PosgreSQL (PL/pgSQL) ` Language Structure ` ` Declarations There are a number of situations that make running small database procedures or functions on the server itself ` Parameters and Types preferable ` Special Statements Basi di Dati ` Control Structures ` Triggers ` These small programs are historically known as database stored procedures PL / pgSQL Reading: ` SQL:1999 standard calls them persistent stored modules (PSM) ` PostgreSQL 8.3 Documentation Chapter V.38 PL / pgSQL PL / pgSQL 3 4 Use Stored Procedures Declaring a Stored Procedure SQL/Persistent Stored Modules (PSM) ` When: ` ` SQL:1999 Standard introduces PSM Commercial DBMS allow writing stored procedures ` Several applications need the same procedure, combining SQL and general purpose languages ` It is a programming language that contains: ` Data transfer should be reduced, ` Statements to create procedures and functions, and ` Tighter security control is needed, ` Procedural programming constructs for writing the body of a ` A stored procedure can be either a procedure or a ` More complex types of derived data should be made available procedure or a function to users, function ` The body can also be a pure SQL statement ` Complex constraints, that cannot be specified by SQL declarative mechanisms, are needed ` Procedural constructs include: ` It is stored as a database object and can be: ` Efficient execution of precompiled procedures is needed ` Conditional IF/THEN/ELSE constructs, and ` Used in SELECT statements, or ` Several looping constructs: ` Stored procedures allow for greater flexibility, if they are ` Called from within JDBC transaction programs, where a ` WHILE/DO/END WHILE changed all programs that call them remain intact CollableStatement object has to be used ` REPEAT/UNTIL/END REPEAT PL / pgSQL PL / pgSQL PL / pgSQL 5 6 7
  • 2. User Defined Functions The basic PostgreSQL UDF Syntax A Simple SQL Function ` ` A DBMS comes with many predefined functions A user defined function may be written using SQL ` Integer addition, CREATE FUNCTION poundtokg(float) ` String concatenation RETURNS float CREATE [ OR REPLACE ] FUNCTION AS ‘SELECT $1*0.545;’ ` An ORDBMS allows users to define new functions LANGUAGE ‘SQL’; name ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ` These functions are called server side functions since they SELECT poundtokg(3.0); [ RETURNS rettype ] reside at the database server AS 'definition' poundtokg ` Unlike client side functions, server side functions may be LANGUAGE langname -------------------- used from within SQL statements 1.635 (1 row) ` Each server side function may be called from any client side program ` $1 is a positional parameter PL / pgSQL PL / pgSQL PL / pgSQL 8 9 10 What is PL/pgSQL Advantages of using PL/pg SQL Supported Data Types ` Conventional queries: ` ` PL/pgSQL is a language that combines: PL/pgSQL functions accept as arguments and can return ` Each SQL statement is submitted from a client to the database as results any of the following data types: ` The expressive power of SQL with server for execution ` Scalar (base and user defined), ` The more typical features of a procedural programming ` The server returns each result to the client language: ` Array, ` This incurs inter process communication and may incur ` Control structures ` Composite (row type), network overhead ` Complex computation ` Record (a placeholder whose structure is defined by the calling ` User defined functions written in PL/pgSQL: ` Exception handling query) ` Reside on database server ` It is aimed for: ` Polymorphic types (anyelement or anyarray), ` Compile once per duration of a database connection ` Creating user defined functions ` Set, ` Can comprise several SQL queries connected by procedural ` Creating trigger procedures constructs ` Void (no useful return value), and ` ` All SQL queries of a function are executed with no Efficient execution (vaguely speaking it is precompiled) ` Null intermediate client/server communication ` Easy of use PL / pgSQL PL / pgSQL PL / pgSQL 11 12 13
  • 3. Record Type Body of a PL/pgSQL Function Language Structure ` PL/pgSQL is a block structured language ` Variables of the record type have no predefined ` Each block starts with either a DECLARE, or BEGIN statement CREATE OR REPLACE FUNCTION some_func() structure ` Ends with an END; statement RETURNS <data_type> AS ` They take on the actual row structure of the row they are ` Each block can contain another block (also called subblock) assigned to during a SELECT command BEGIN $$ --start of the body ` The structure of a record variable can change each time statements -- here comes the function body it is assigned to BEGIN [DECLARE declarations] statemnets ` The record type is not a true type, only a record END; BEGIN --denotes start of block statements placeholder END; END;--denotes the end of a block $$ --end of the body ` BEGIN/END statements do not denote the start and the end of a transaction, but only the boundaries of a block LANGUAGE ‘plpgsql’; PL / pgSQL PL / pgSQL PL / pgSQL 14 15 16 Declarations Function Parameters (1) Function Parameters (2) ` There are two ways to define function parameters ` ` The other way to define function parameters is All variables in a block must be declared in the ` One is to define their types only declaration section of the block (the only exception is the CREATE FUNCTION area(a int, b int) variable of the for loop, which is an integer by CREATE FUNCTION area(int, int) RETURNS int default) RETURNS int AS $$ ` Examples: AS $$ BEGIN ` BEGIN StudenName varchar;--initialized to null RETURN a*b; RETURN $1*$2; ` NumOfMarks real := 100.00; --assignment END; END; ` Grade char(2) DEFAULT 'A+'; $$ LANGUAGE 'plpgsql'; $$ LANGUAGE 'plpgsql'; ` ` Here, a contains the value of the first parameter, and b Here, $1 contains the value of the first parameter, and $2 contains the value of the second parameter contains the value of the second parameter PL / pgSQL PL / pgSQL PL / pgSQL 17 18 19
  • 4. Functions in SQL Queries With Tables Functions in SQL Queries With Tables RETURN Statement ` To return single valued data from a function we use: ` A powerful use of functions is in queries that retrieve data CREATE OR REPLACE FUNCTION from tables RETURN expression area(real, real) RETURNS real statement AS 'SELECT $1*$2;' LANGUAGE 'SQL'; CREATE TABLE Rectangle (RectId int, a real, b real); ` The RETURN statement with expression terminates INSERT INTO Rectangle VALUES(1, 5.5, 6.6); the function and returns the value of the expression SELECT RectId, area(a, b) as Rec_Area to the caller INSERT INTO Rectangle VALUES(2, 3.3, 4.4); FROM Rectangle; ` The return value of a function must be defined: ` If control reaches the end of the top level block without hitting RectId a b a RETURN statement, a run time error will occur RectId Rec_Area ` 1 5.5 6.6 Even if the function’s return value is declared to be void, a 1 36.3 RETURN statement must still be provided (but will return 2 3.3 4.4 nothing) 2 14.52 PL / pgSQL PL / pgSQL PL / pgSQL 20 21 22 Example 1 SELECT . . . INTO (1) SELECT . . .INTO (2) ` If a SELECT command returns no rows, null values are ` The result of a SELECT command yielding multiple assigned to the target DECLARE columns (but only one row) can be assigned to a record s record; variable ` If a SELECT command returns multiple rows only one of the BEGIN them, the first one retrieved is assigned to the target, SELECT * INTO s FROM student WHERE studentid=4; SELECT <attrbute_list> INTO <target> IF s.StudentId IS NULL THEN DECLARE s record; --s is the target RAISE NOTICE 'There is no student with id = 4'; FROM… BEGIN RETURN NULL; SELECT * INTO s FROM Student; ELSE RETURN s; RETURN s; ` If the target type is record, it automatically END; END IF; configures to the query result END; ` If the table is empty, s will be (, , , ) – a structure with null components PL / pgSQL PL / pgSQL PL / pgSQL 23 24 25
  • 5. Example 2 Obtaining the Result Status (FOUND) An Example for the FOUND Variable ` To determine the result of a command, you can check a DECLARE DECLARE special variable named FOUND of the type boolean t record; t record; BEGIN BEGIN IF p < 0 THEN --p is a variable SELECT * INTO t FROM Grades ` The following commands set FOUND: SELECT * INTO t FROM Student WHERE StudentId = 007 AND CourseId= 'COMP302'; ` SELECT...INTO... sets it true if it returns any row, false WHERE StudentId = 007; IF NOT FOUND THEN otherwise ELSE SELECT * INTO t FROM Student ` PERFORM sets it true if it returns (and discards) any row, false SELECT * INTO t FROM Grades WHERE StudentId = 007; otherwise WHERE StudentId = 007 AND CourseId ='COMP302'; END IF; END IF; RETURN t; ` UPDATE, INSERT, and DELETE set it true if at least one return t; END; row is affected, false otherwise END; ` FOUND is a local variable within each PL/pgSQL function PL / pgSQL PL / pgSQL PL / pgSQL 26 27 28 Control Statements RAISE Statement A RAISE NOTICE Example ` PL/pgSQL supports different forms of IF conditional: DECLARE ` Even though PL/pgSQL doesn’t offer a way to intercept ` From: errors, the RAISE statement is provided to raise an error s record; ` IF. . .THEN. . .END IF; BEGIN ` To: SELECT * INTO s FROM Student; ` Syntax: ` IF. . .THEN. . .ELSEIF. . .THEN. . .ELSE. . . IF NOT FOUND THEN END IF; RAISE severity 'message' [, variable []]; ` Also, PL/pgSQL supports the following looping statements: RAISE NOTICE 'Table is empty'; where severity can be: ` LOOP, RETURN null; ` DEBUG ` EXIT, ELSE ` NOTICE – just to send a message to the client application ` WHILE, and RETURN s; ` EXCEPTION – to raise an exception, which is handled as ` FOR END IF; described in the manual ` Have a look in the manual for particulars END; PL / pgSQL PL / pgSQL PL / pgSQL 29 30 31
  • 6. Next topic The Trigger Syntax Trigger Procedures in PL/pg SQL ` ` Triggers A trigger procedure is created with <trigger>::= CREATE TRIGGER <trigger_name> CREATE FUNCTION {AFTER | BEFORE} <triggering_event> [OR...] command, which: ON <table_name> ` Does not have any parameters, and [FOR [EACH] { ROW | STATEMENT }] ` Has a trigger return type EXECUTE PROCEDURE <function_name>(arguments); <triggering_events>::= ` When a PL/pgSQL function is called as a trigger, several <triggerng_event> [OR <triggering_event>…..] special variables are created automatically in the top level block <triggering_event>::= {INSERT | DELETE | UPDATE} PL / pgSQL PL / pgSQL PL / pgSQL 32 33 34 Automatically Created Variables RETURN Type Returning a Value Being Not NULL ` A row level trigger fired BEFORE may return NULL to ` ` The most important automatically created variables: A trigger has to return: signal the trigger manager to skip the rest of operations ` Either NULL, or ` NEW of data type RECORD holding the new database row for for this row (the INSERT/DELETE/UPDATE will not be ` A record/row value having exactly the structure of the table INSERT/UPDATE operations in row level triggers executed for this row) the trigger was fired for ` OLD of data type RECORD holding the old database row for UPDATE/DELETE operations in row level triggers ` If a BEFORE row level trigger returns a non null value, ` The return value of a: the operation proceeds with that row value: ` BEFORE or AFTER per statement trigger, or ` There are also other variables generated (have a look in ` Returning a row value different from the original value of NEW ` alters the row that will be inserted or updated (but has no An AFTER row level trigger is always ignored the PostgreSQL Manual) influence on delete operation) ` Both should be NULL ` Altering a row to be stored is accomplished either by replacing ` But they can still abort an entire operation by raising en error single values directly in NEW, or building a completely new record/row PL / pgSQL PL / pgSQL PL / pgSQL 35 36 37
  • 7. Triggers Examples Summary (1) Referential Integrity Trigger INSERT ` ` Consider the following part of a relational database Stored Procedures have a widespread use in industry CREATE TRIGGER ins_ref_int schema: since they allow for: BEFORE INSERT ON Exam FOR EACH ROW EXECUTE PROCEDURE ins_ref_int(); ` Code sharing, ` CREATE OR REPLACE FUNCTION ins_ref_int() Tighter security control, Student (StudId, Name, NoOfPts, Degree) RETURNS trigger AS $$ ` Efficient execution DECLARE s RECORD; Exam (StudId, CourseId, Term, Grade) BEGIN ` User Defined Functions (UDFs): SELECT * INTO s FROM Student WHERE NEW.StudId = StudId; ` IF NOT FOUND THEN Can be defined using SQL only, or a combination of SQL and a ` Suppose DBMS does not support referential integrity RAISE NOTICE 'There is no student %', NEW.StudId; procedural language RETURN NULL; constraints ` ELSE Can be used as stored procedures, RETURN NEW; ` Can be used as trigger procedures END IF; END; $$ LANGUAGE 'PLpgSQL'; PL / pgSQL PL / pgSQL PL / pgSQL 38 39 40 Summary (2) Summary (3) ` PL/pgSQL is a simple language that combines procedural constructs with ` Triggers are active rules that are automatically fired when SQL statements an event occurs ` It is designed to provide for: ` In the PostgreSQL environment triggers use PL/pgSQL ` Creating user defined functions procedures ` Creating trigger procedures ` Triggers are extensively used to implement constraints ` Efficient execution (vaguely speaking it is precompiled) ` Easy to use ` It is block structured ` Supports ` A waste range of data types ` Conditionals ` Looping ` Special statements (SELECT INTO) PL / pgSQL PL / pgSQL 41 42