PL/pgSQL http://www.commandprompt.com/ppbook/.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Objectives In this chapter, you will learn about:
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 4B: More Advanced PL/SQL Programming
Introduction to Structured Query Language (SQL)
Linux+ Guide to Linux Certification, Second Edition
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to Structured Query Language (SQL)
Introduction to C Programming
Adding Automated Functionality to Office Applications.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Using the Select Case Statement and the MsgBox Function (Unit 8)
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Linux+ Guide to Linux Certification, Third Edition
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
CPS120: Introduction to Computer Science Decision Making in Programs.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
JavaScript, Fourth Edition
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Stored Procedure used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Views, Sequence, and Stored Procedure used in PosgreSQL.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Controlling Program Flow with Decision Structures.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Learning Javascript From Mr Saem
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Linux Administration Working with the BASH Shell.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Web Database Programming Using PHP
Chapter 2 - Introduction to C Programming
Web Database Programming Using PHP
Handling Exceptions.
The Selection Structure
Scripts & Functions Scripts and functions are contained in .m-files
Chapter 2 - Introduction to C Programming
Stored Procedure used in PosgreSQL
PL/SQL Scripting in Oracle:
Chapter 10 Programming Fundamentals with JavaScript
PRACTICE OVERVIEW PL/SQL Part - 2.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Stored Procedure used in PosgreSQL
Stored Procedure used in PosgreSQL
Chapter 2 - Introduction to C Programming
CS4222 Principles of Database System
Stored Procedure used in PosgreSQL
Chapter 2 - Introduction to C Programming
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Presentation transcript:

PL/pgSQL http://www.commandprompt.com/ppbook/

Definition PL/pgSQL is a loadable, procedural language, similar to the Oracle procedural language, PL/SQL. A procedural language is a programming language used to specify a sequence of steps that are followed to produce an intended programmatic result.

Advantages group sequences of SQL and programmatic statements together within a database server reduces network and communications overhead

Adding PL/pgSQL to Database To add PL/pgSQL you can either use the createlang application from command prompt, or the CREATE LANGUAGE SQL command from within a database client such as psql CREATE LANGUAGE command first requires the creation of the PL/pgSQL call handler, which is the function that actually processes and interprets the PL/pgSQL code.

Example CREATE FUNCTION CREATE FUNCTION plpgsql_call_handler() RETURNS OPAQUE AS '/postgres_library_path/plpgsql.so' LANGUAGE 'C' postgres_library_path is the absolute system path to the installed PostgreSQL library files. This path, by default, is /usr/local/pgsql/lib

Adding Language Previous example only creates the function handler; the language itself must be added with the CREATE LANGUAGE command.

Syntax to add Language CREATE LANGUAGE 'plpgsql' HANDLER plpgsql_call_handler LANCOMPILER 'PL/pgSQL‘ plpgsql is the name of the language to be created, the plpgsql_call_handler is the name of the call handler function created in the previous example. LANCOMPILER is the keyword and PL/pgSQL is an arbitrary descriptive note

Adding PL/pgSQL with CREATE LANGUAGE CREATE LANGUAGE 'plpgsql' HANDLER plpgsql_call_handler LANCOMPILER 'PL/pgSQL'; The name following the HANDLER keyword should be the same name which is used to create the call handler

Example createlang Using createlang as a database superuser $ cd /usr/local/pgsql/bin booktown=# createlang plpgsql booktown Explicitly passing a superuser account name to createlang $ cd /usr/local/pgsql/bin/ $ createlang plpgsql -U manager booktown The createlang program will return you to a shell prompt upon successful execution

Language Structure PL/pgSQL's structure is similar to other programming languages such as C ach portion of code acts as a function all variables must be declared before being used code segments accept arguments when called and return arguments at their end PL/pgSQL functions are case insensitive

Code Blocks PL/pgSQL code is organized in blocks of code (block structured code ) Code blocks are entered within a SQL CREATE FUNCTION CREATE FUNCTION command names the new function states its argument types states the return type

Code Blocks (contd.) function's main code block starts with a declaration section variables are declared and optionally initialized to a default value variable declaration specifies the variable's name and type the main body of the code block is started with the BEGIN keyword

Code Blocks (contd.) END keyword designates the end of the code block PL/pgSQL function should return a value of its specified return type before its END keyword is reached

The structure of a code block CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declaration; [...] BEGIN statement; END; ' LANGUAGE 'plpgsql'; PL/pgSQL code can contain an unlimited amount of sub-blocks

Comments Using single-line comments Using block comments -- This will be interpreted as a single-line comment Using block comments /* *This is a *block *comment. */

Statements and Expressions PL/pgSQL code is composed of statements and expressions Most of your code will be made of statements Expressions are essential to certain types of data manipulation

Statements statement performs an action within PL/pgSQL code assignment of a value to a variable execution of a query Most of the statements will be placed in the main operation located after the BEGIN keyword and before the END keyword declarative statements appear in the declaration section (after the DECLARE keyword)

Expressions Expressions are calculations or operations Example return their results as one of PostgreSQL's base data types Example x := a + b adds the variables a and b, then assigns the result to the variable x

Example CREATE FUNCTION a_function () RETURNS int4 AS ' DECLARE an_integer int4; BEGIN an_integer := 10 * 10; return an_integer; END; ' LANGUAGE 'plpgsql'; Output booktown=# SELECT a_function() AS output; output -------- 100 (1 row)

Example CREATE FUNCTION add_shipment (integer, text) RETURNS timestamp AS ' DECLARE -- Declare aliases for function arguments. customer_id ALIAS FOR $1; isbn ALIAS FOR $2; -- Declare a variable to hold the shipment ID number and -- the current time. shipment_id INTEGER; right_now timestamp; BEGIN -- Set the current time variable to the string ''now''. right_now := ''now''; -- Order the existing shipments by their ID numbers, beginning -- with the highest number, then insert the first ID number into -- the shipment_id variable. SELECT INTO shipment_id id FROM shipments ORDER BY id DESC; -- Add one to the shipment_id variable. shipment_id := shipment_id + 1;

Example (contd.) -- Insert a shipment record into the shipments table. The -- right_now variable will be typecast to a timestamp at -- run-time, causing constant value now to be interpreted as -- the timestamp each time the function is run. INSERT INTO shipments VALUES ( shipment_id, customer_id, isbn, right_now ); -- Return a timestamp using the constant value now. RETURN right_now; END; ' LANGUAGE 'plpgsql';

The IF/THEN statement CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] END IF; END; ' LANGUAGE 'plpgsql'; More Examples - http://www.commandprompt.com/ppbook/

Example CREATE FUNCTION stock_amount (integer, integer) RETURNS integer AS ' DECLARE -- Declare aliases for function arguments. b_id ALIAS FOR $1; b_edition ALIAS FOR $2; -- Declare variable to store the ISBN number. b_isbn TEXT; -- Declare variable to store the stock amount. stock_amount INTEGER; BEGIN -- This SELECT INTO statement retrieves the ISBN number of the row in -- the editions table that had both the book ID number and edition number -- that were provided as function arguments. SELECT INTO b_isbn isbn FROM editions WHERE book_id = b_id AND edition = b_edition;

Example (contd.) -- Check to see if the ISBN number retrieved is NULL. This will -- happen if there is not an existing book with both the ID number -- and edition number specified in the function arguments. If the -- ISBN is null, the function returns a value of -1 and ends. IF b_isbn IS NULL THEN RETURN -1; END IF; -- Retrieve the amount of books available from the stock table -- and record the number in the stock_amount variable. SELECT INTO stock_amount stock FROM stock WHERE isbn = b_isbn; -- Return the amount of books available. RETURN stock_amount; END; ' LANGUAGE 'plpgsql';

The IF/THEN/ELSE statement CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] ELSE END IF; END; ' LANGUAGE 'plpgsql';

Example CREATE FUNCTION in_stock (integer,integer) RETURNS boolean AS ' DECLARE -- Declare aliases for function arguments. b_id ALIAS FOR $1; b_edition ALIAS FOR $2; -- Declare a text variable to hold the ISBN of the book -- once found. b_isbn TEXT; -- Declare an integer variable to hold the amount of stock. stock_amount INTEGER; BEGIN -- This SELECT INTO statement retrieves the ISBN number of -- the row in the editions table that had both the book ID -- number and edition number that were provided as function -- arguments. SELECT INTO b_isbn isbn FROM editions WHERE book_id = b_id AND edition = b_edition; -- Check to see if the ISBN number retrieved is NULL. This

Example (contd.) -- will happen if there is not an existing book with both the -- ID number and edition number specified in the function -- arguments. If the ISBN is null, the function returns a -- FALSE value and ends. IF b_isbn IS NULL THEN RETURN FALSE; END IF; -- Retrieve the amount of books available from the stock -- table and record the number in the stock_amount variable. SELECT INTO stock_amount stock FROM stock WHERE isbn = b_isbn; -- Use an IF/THEN/ELSE check to see if the amount of books -- available is less than or equal to 0. If so, return FALSE. -- If not, return TRUE. IF stock_amount <= 0 THEN ELSE RETURN TRUE; END; ' LANGUAGE 'plpgsql';

The IF/THEN/ELSE/IF statement CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] ELSE IF condition END IF; END; ' LANGUAGE 'plpgsql';

Example CREATE FUNCTION books_by_subject (text) RETURNS text AS ' DECLARE -- Declare an alias for user input, which should be either all -- or the name of a subject. sub_title ALIAS FOR $1; -- Declare an integer to store the subject ID in, and a text -- variable to store the list of found books. The text variable -- is set to a blank string. sub_id INTEGER; found_text TEXT :=''''; BEGIN -- Retrieve the subject ID number for the book matching the -- title supplied by the user.

Example (contd.) SELECT INTO sub_id id FROM subjects WHERE subject = sub_title; -- Check to see if the function was given all as the the subject -- name. If so, execute the SELECT INTO statement and return -- the found_text variable. IF sub_title = ''all'' THEN found_text extract_all_titles(); RETURN found_text; -- If the function was NOT sent all as the name of the subject, -- check to see the subject ID number turned out to be within -- the valid range of subjects. If it did, execute the -- extract_title() function with the subject ID number as its -- argument, then assign the result to the found_text variable. ELSE IF sub_id >= 0 THEN found_text := extract_title(sub_id); RETURN ''\n'' || sub_title || '':\n'' || found_text;

Example (contd.) -- If the subject ID number was NULL, return a message telling -- the user that the subject specified could not be found. ELSE IF sub_id IS NULL THEN RETURN ''Subject not found.''; END IF; RETURN ''An error occurred. .''; END; ' LANGUAGE 'plpgsql';

Loops an unconditional loop will execute the statements within its body until an EXIT statement is reached the EXIT keyword can be accompanied by WHEN, followed by and an expression to specify when the loop should exit the expression should be a Boolean expression LOOP statement; [...] END LOOP;

Loops (contd.) When terminating a loop with EXIT, you may optionally specify a label and/or a condition on which the loop should exit from A label is an arbitrary identifier, prefixed with a pair of less-than symbols (<<) and suffixed with a pair of greater-than symbols (>>) <<label_name>> LOOP […] END LOOP;

Loops (contd.) By providing a label, you can specify which loop to exit when you have several loops nested inside each other the use of labels in EXIT will only work if you have specified a label for the loop you are attempting to terminate [ <<label>> ] LOOP statement; [...] EXIT [ label ] [ WHEN condition ]; END LOOP;

Example CREATE FUNCTION square_integer_loop (integer) RETURNS integer AS ' DECLARE -- Declare aliases for function argument. num1 ALIAS FOR $1; -- Declare an integer to hold the result. result integer; BEGIN -- Assign the user input number to the result variable. result := num1; LOOP result := result * result; EXIT WHEN result >= 10000; END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql';

The WHILE loop The WHILE loop is used to loop through a block of statements until a specified condition becomes false [ <<label>> ] WHILE condition LOOP statement; [...] END LOOP;

Example CREATE FUNCTION add_two_loop (integer, integer) RETURNS integer AS ' DECLARE -- Declare aliases for function arguments. low_number ALIAS FOR $1; high_number ALIAS FOR $2; -- Declare a variable to hold the result. result INTEGER = 0; BEGIN -- Add one to the variable result until the value of result is -- equal to high_number. WHILE result != high_number LOOP result := result + 1; END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql';

The FOR loop The structure of a FOR loop in PL/pgSQL is similar to FOR loops in other procedural languages [ <<label>> ] FOR identifier IN [ REVERSE ] expression1 .. expression2 LOOP statement; [...] END LOOP;

Example CREATE FUNCTION extract_all_titles2 () RETURNS text AS ' DECLARE -- Declare a variable for the subject ID number. sub_id INTEGER; -- Declare a variable to hold the list of titles. text_output TEXT = '' ''; -- Declare a variable to hold the subject title. sub_title TEXT; -- Declare a variable to hold records from the books table. row_data books%ROWTYPE; BEGIN -- Outer FOR loop: loop through the body of this loop until the -- variable i equals 15. Start the looping at 0. Essentially, --loop the following statements 16 times (once for each subject). FOR i IN 0..15 LOOP

Example (contd.) -- Retrieve the subject name of the subject with an ID number -- that matches the variable i. SELECT INTO sub_title subject FROM subjects WHERE id = i; -- Insert the subject name, a colon, and a new line into the -- text_output variable. text_output = text_output || ''\n'' || sub_title || '':\n''; -- Loop through all records in the books table with a subject ID FOR row_data IN SELECT * FROM books WHERE subject_id = i LOOP -- Insert the title of a matching book into the text_output -- variable, followed by a newline. text_output := text_output || row_data.title || ''\n''; END LOOP; -- Return the list. RETURN text_output; END; ' LANGUAGE 'plpgsql';