86
IBM Netezza Release 7.1 IBM Netezza Stored Procedures Developer's Guide

IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Embed Size (px)

Citation preview

Page 1: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

IBM NetezzaRelease 7.1

IBM Netezza Stored ProceduresDeveloper's Guide

���

Page 2: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des
Page 3: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

IBM NetezzaRelease 7.1

IBM Netezza Stored ProceduresDeveloper's Guide

���

Page 4: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

NoteBefore using this information and the product it supports, read the information in “Notices” on page C-1

Revised: January 10, 2014

This edition applies to IBM Netezza Release 7.1 and to all subsequent releases until otherwise indicated in neweditions.

© Copyright IBM Corporation 2009, 2014.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.

Page 5: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Contents

Electronic emission notices . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Regulatory and compliance . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

About this publication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiIf you need help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiHow to send your comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Chapter 1. Introduction to stored procedures . . . . . . . . . . . . . . . . . . . 1-1Stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1

NZPLSQL language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2SQL commands for stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Stored procedures input and return types . . . . . . . . . . . . . . . . . . . . . . . . 1-2

How to create and use a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . 1-3How to execute a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Best practices for stored procedure developers . . . . . . . . . . . . . . . . . . . . . . . 1-3

Security considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Cross-database access to stored procedures . . . . . . . . . . . . . . . . . . . . . . . 1-4Block quoting support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5SQL restrictions within the stored procedure . . . . . . . . . . . . . . . . . . . . . . . 1-6

Best practices for Netezza administrators . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Back up and restore stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Upgrade and patch Netezza systems that have stored procedures . . . . . . . . . . . . . . . . 1-7Downgrade Netezza systems that have stored procedures . . . . . . . . . . . . . . . . . . 1-7

Chapter 2. NZPLSQL statements and grammar . . . . . . . . . . . . . . . . . . 2-1NZPLSQL structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

Transaction commits and rollbacks in stored procedures . . . . . . . . . . . . . . . . . . . 2-2AUTOCOMMIT ON blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4Variables and constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5

Parameter passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Argument list and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Scope of variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Data types and aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9

Array variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11

Literals and math operations in expressions . . . . . . . . . . . . . . . . . . . . . . . 2-12Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15

Assignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15Call another procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16Run dynamic queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16Obtain other results status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Return from a procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17

Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Conditional control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Iterative control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19

Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20Iterate through the records of a query . . . . . . . . . . . . . . . . . . . . . . . . . 2-21

Report messages and raise errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22Exceptions and error messages support . . . . . . . . . . . . . . . . . . . . . . . . . 2-23Return a result set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25

© Copyright IBM Corp. 2009, 2014 iii

Page 6: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

REFTABLE and ROLLBACK commands . . . . . . . . . . . . . . . . . . . . . . . . 2-27Manage large data sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-27

Advanced development topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28Extend the NZPLSQL language with UDFs . . . . . . . . . . . . . . . . . . . . . . . 2-28Tips and best practices for stored procedures . . . . . . . . . . . . . . . . . . . . . . 2-28

Chapter 3. Create and manage stored procedures . . . . . . . . . . . . . . . . . 3-1Manage user account permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Create a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

Design a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4Create a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4Size-specific, generic, and variable argument procedures . . . . . . . . . . . . . . . . . . . 3-5Obfuscate the procedure body . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8

Call or invoke a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10Alter a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10Comment on a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11Drop a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12Show information about a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . 3-12NzAdmin administrative interface for stored procedures. . . . . . . . . . . . . . . . . . . . 3-12

Appendix A. SQL command reference . . . . . . . . . . . . . . . . . . . . . . A-1The ALTER PROCEDURE command . . . . . . . . . . . . . . . . . . . . . . . . . . A-1The CALL and EXEC[UTE [PROCEDURE]] commands . . . . . . . . . . . . . . . . . . . . A-3The CREATE [OR REPLACE] PROCEDURE commands . . . . . . . . . . . . . . . . . . . . A-5The DROP PROCEDURE command . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7The SHOW PROCEDURE command . . . . . . . . . . . . . . . . . . . . . . . . . . A-9

Appendix B. Stored procedure examples . . . . . . . . . . . . . . . . . . . . B-1Variable argument stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . B-1Example of simulating an anonymous block . . . . . . . . . . . . . . . . . . . . . . . . B-2

Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C-1Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C-3

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X-1

iv IBM Netezza Stored Procedures Developer's Guide

Page 7: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Electronic emission notices

When you attach a monitor to the equipment, you must use the designatedmonitor cable and any interference suppression devices that are supplied with themonitor.

Federal Communications Commission (FCC) Statement

This equipment was tested and found to comply with the limits for a Class Adigital device, according to Part 15 of the FCC Rules. These limits are designed toprovide reasonable protection against harmful interference when the equipment isoperated in a commercial environment. This equipment generates, uses, and canradiate radio frequency energy and, if not installed and used in accordance withthe instruction manual, might cause harmful interference to radio communications.Operation of this equipment in a residential area is likely to cause harmfulinterference, in which case the user is required to correct the interference at theirown expense.

Properly shielded and grounded cables and connectors must be used to meet FCCemission limits. IBM® is not responsible for any radio or television interferencecaused by using other than recommended cables and connectors or byunauthorized changes or modifications to this equipment. Unauthorized changesor modifications might void the authority of the user to operate the equipment.

This device complies with Part 15 of the FCC Rules. Operation is subject to thefollowing two conditions: (1) this device might not cause harmful interference, and(2) this device must accept any interference received, including interference thatmight cause undesired operation.

Industry Canada Class A Emission Compliance Statement

This Class A digital apparatus complies with Canadian ICES-003.

Avis de conformité à la réglementation d'Industrie Canada

Cet appareil numérique de la classe A est conforme à la norme NMB-003 duCanada.

Australia and New Zealand Class A Statement

This product is a Class A product. In a domestic environment, this product mightcause radio interference in which case the user might be required to take adequatemeasures.

European Union EMC Directive Conformance Statement

This product is in conformity with the protection requirements of EU CouncilDirective 2004/108/EC on the approximation of the laws of the Member Statesrelating to electromagnetic compatibility. IBM cannot accept responsibility for anyfailure to satisfy the protection requirements resulting from a nonrecommendedmodification of the product, including the fitting of non-IBM option cards.

© Copyright IBM Corp. 2009, 2014 v

Page 8: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

This product is an EN 55022 Class A product. In a domestic environment, thisproduct might cause radio interference in which case the user might be required totake adequate measures.

Responsible manufacturer:

International Business Machines Corp.New Orchard RoadArmonk, New York 10504914-499-1900

European Community contact:

IBM Technical Regulations, Department M456IBM-Allee 1, 71137 Ehningen, GermanyTelephone: +49 7032 15-2937Email: [email protected]

Germany Class A Statement

Deutschsprachiger EU Hinweis: Hinweis für Geräte der Klasse A EU-Richtliniezur Elektromagnetischen Verträglichkeit

Dieses Produkt entspricht den Schutzanforderungen der EU-Richtlinie2004/108/EG zur Angleichung der Rechtsvorschriften über die elektromagnetischeVerträglichkeit in den EUMitgliedsstaaten und hält die Grenzwerte der EN 55022Klasse A ein.

Um dieses sicherzustellen, sind die Geräte wie in den Handbüchern beschrieben zuinstallieren und zu betreiben. Des Weiteren dürfen auch nur von der IBMempfohlene Kabel angeschlossen werden. IBM übernimmt keine Verantwortung fürdie Einhaltung der Schutzanforderungen, wenn das Produkt ohne Zustimmung derIBM verändert bzw. wenn Erweiterungskomponenten von Fremdherstellern ohneEmpfehlung der IBM gesteckt/eingebaut werden.

EN 55022 Klasse A Geräte müssen mit folgendem Warnhinweis versehen werden:“Warnung: Dieses ist eine Einrichtung der Klasse A. Diese Einrichtung kann imWohnbereich Funk-Störungen verursachen; in diesem Fall kann vom Betreiberverlangt werden, angemessene Maßnahmen zu ergreifen und dafüraufzukommen.”

Deutschland: Einhaltung des Gesetzes über dieelektromagnetische Verträglichkeit von Geräten

Dieses Produkt entspricht dem “Gesetz über die elektromagnetische Verträglichkeitvon Geräten (EMVG)”. Dies ist die Umsetzung der EU-Richtlinie 2004/108/EG inder Bundesrepublik Deutschland.

Zulassungsbescheinigung laut dem Deutschen Gesetz über dieelektromagnetische Verträglichkeit von Geräten (EMVG) (bzw. derEMC EG Richtlinie 2004/108/EG) für Geräte der Klasse A

Dieses Gerät ist berechtigt, in Übereinstimmung mit dem Deutschen EMVG dasEG-Konformitätszeichen - CE - zu führen.

Verantwortlich für die Einhaltung der EMV Vorschriften ist der Hersteller:

vi IBM Netezza Stored Procedures Developer's Guide

Page 9: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

International Business Machines Corp.New Orchard RoadArmonk, New York 10504914-499-1900

Der verantwortliche Ansprechpartner des Herstellers in der EU ist:

IBM DeutschlandTechnical Regulations, Department M456IBM-Allee 1, 71137 Ehningen, GermanyTelephone: +49 7032 15-2937Email: [email protected]

Generelle Informationen: Das Gerät erfüllt die Schutzanforderungen nach EN 55024und EN 55022 Klasse A.

Japan VCCI Class A Statement

This product is a Class A product based on the standard of the Voluntary ControlCouncil for Interference (VCCI). If this equipment is used in a domesticenvironment, radio interference might occur, in which case the user might berequired to take corrective actions.

Japan Electronics and Information Technology IndustriesAssociation (JEITA) Statement

Japan Electronics and Information Technology Industries Association (JEITA)Confirmed Harmonics Guidelines (products less than or equal to 20 A per phase)

Japan Electronics and Information Technology IndustriesAssociation (JEITA) Statement

Japan Electronics and Information Technology Industries Association (JEITA)Confirmed Harmonics Guidelines (products greater than 20 A per phase)

Electronic emission notices vii

Page 10: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Korea Communications Commission (KCC) Statement

This is electromagnetic wave compatibility equipment for business (Type A). Sellersand users need to pay attention to it. This is for any areas other than home.

Russia Electromagnetic Interference (EMI) Class A Statement

People's Republic of China Class A Electronic EmissionStatement

Taiwan Class A Compliance Statement

viii IBM Netezza Stored Procedures Developer's Guide

Page 11: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Regulatory and compliance

Regulatory Notices

Install the NPS® system in a restricted-access location. Ensure that only thosepeople trained to operate or service the equipment have physical access to it.Install each AC power outlet near the NPS rack that plugs into it, and keep itfreely accessible.

Provide approved circuit breakers on all power sources.

Product might be powered by redundant power sources. Disconnect ALL powersources before servicing.

High leakage current. Earth connection essential before connecting supply. Courantde fuite élevé. Raccordement à la terre indispensable avant le raccordement auréseau.

Homologation Statement

This product may not be certified in your country for connection by any meanswhatsoever to interfaces of public telecommunications networks. Furthercertification may be required by law prior to making any such connection. Contactan IBM representative or reseller for any questions.

© Copyright IBM Corp. 2009, 2014 ix

Page 12: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

x IBM Netezza Stored Procedures Developer's Guide

Page 13: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

About this publication

IBM Netezza® stored procedures combine the benefits of SQL to query andmanipulate database information with the benefits of a procedural programminglanguage to handle data processing, transaction logic, and application branchingbehaviors.

Review the topics in this publication to create and use stored procedures on a IBMNetezza data warehouse appliance. These topics describe the NZPLSQL Netezzaprocedural language, provide an overview of the language and statements, andhow to create, alter, and drop procedures by using Netezza SQL commands.

To use these topics, you should be familiar with the Netezza systems andarchitecture and Netezza SQL commands and how to access a Netezza database.You should also be familiar with the general concepts of stored procedures, how tocreate structured language programs, and how to debug applications.

If you need helpIf you are having trouble using the IBM Netezza appliance, follow these steps:1. Try the action again, carefully following the instructions for that task in the

documentation.2. Go to the IBM Support Portal at: http://www.ibm.com/support. Log in using

your IBM ID and password. You can search the Support Portal for solutions. Tosubmit a support request, click the Service Requests & PMRs tab.

3. If you have an active service contract maintenance agreement with IBM, youcan contact customer support teams by telephone. For individual countries,visit the Technical Support section of the IBM Directory of worldwide contacts(http://www.ibm.com/support/customercare/sas/f/handbook/contacts.html).

How to send your commentsYou are encouraged to send any questions, comments, or suggestions about theIBM Netezza documentation. Send an email to [email protected] include the following information:v The name and version of the manual that you are usingv Any comments that you have about the manualv Your name, address, and phone number

We appreciate your suggestions.

© Copyright IBM Corp. 2009, 2014 xi

Page 14: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

xii IBM Netezza Stored Procedures Developer's Guide

Page 15: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Chapter 1. Introduction to stored procedures

This section provides an overview of the support for stored procedures in the IBMNetezza family of data warehouse appliances.

Stored procedure support is available in Netezza Release 4.6 and later. These topicsdescribe changes available in Release 7.1 and later.

Stored proceduresIBM Netezza stored procedures combine the benefits of SQL to query andmanipulate database information with the benefits of a procedural programminglanguage to handle data processing, transaction logic, and application branchingbehaviors.

For example, if you have a database that contains customer information, inventory,and sales records, you might also have an application that processes the sale of anitem in inventory. When an order request arrives, the application might bedesigned to query the database to determine how many items of that type areavailable in inventory, and then to take the following actions:v If the available inventory is less than the order number, the application processes

the request for the available number and notifies an order administrator to ordermore inventory to complete the purchase.

v If the available inventory is greater than the order request, the applicationprocesses the order and updates the database to show the reduction in thecurrent inventory.

v If the inventory is discontinued, the application saves the order request andreturns a message that the item is no longer available. It can also query forrelated or replacement inventory to report alternative merchandise.

While such an application can be managed with a third-party business applicationthat accesses the Netezza database to do these tasks, you can also use Netezzastored procedures to encapsulate this application as an object in the Netezzadatabase. SQL provides the power to access and update the database informationabout the host, and the procedure language provides the logic for if-then-elsebranching and application processing.

Because the application is on the Netezza host, the application performance canbenefit from its location “onsite” by avoiding the network time between anapplication client system and the Netezza host. The application itself also becomeseasier to maintain, as it is in only one location (the Netezza host) and thusversioning and updates need only be made in one place to keep the applicationup-to-date for all users.

With Netezza stored procedures, you can also take advantage of security andaccess benefits. Stored procedures can be defined to run with the credentials of theuser who created the procedure or the credentials of the user who is running theprocedure. The procedure manages the access to information contained in variousbase tables and views. You can grant a user permission to run a stored procedurewithout granting that user explicit access to underlying tables or views.

© Copyright IBM Corp. 2009, 2014 1-1

Page 16: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

NZPLSQL language

You implement stored procedures on the IBM Netezza host by creatingapplications by using the NZPLSQL language. NZPLSQL is an interpretedlanguage which is based on Postgres PL/pgSQL language and designed for theNetezza host environment.

NZPLSQL is a scripting language embedded in SQL. As a procedural language, ithas branch, loop, and subprogram structures while SQL provides the mainprogram. The subprograms, known as procedures, can take arguments and declareinternal variables. After they are stored in a database, these procedures can becalled from within other databases on the same Netezza host.

The NZPLSQL language provides for the following types of procedural logic:v Conditionals (if/else)v Looping (while, for)v Execution of SQL (including dynamic SQL)v Variablesv Returning a scalar result or a result setv Input argumentsv Execution in the calling context (session and transaction)v Extending functionality (adding NZPLSQL library routines)

SQL commands for stored procedures

To support stored procedures in the IBM Netezza database, the Netezza SQLlanguage includes commands for stored procedures:v ALTER PROCEDUREv CALL or EXEC[UTE[ PROCEDURE]]v CREATE [OR REPLACE] PROCEDUREv DROP PROCEDUREv SHOW PROCEDURE

You can use any SQL tool that supports ODBC, JDBC, OLE-DB to enter thesecommands. This publication contains examples that use the nzsql command-linetool.

In addition to these procedure-specific commands, you can also use the commandsGRANT and REVOKE to allow or deny access to procedures, and COMMENT ONto add descriptions and details to the procedure definitions.Related concepts:Chapter 3, “Create and manage stored procedures,” on page 3-1Related reference:Appendix A, “SQL command reference,” on page A-1

Stored procedures input and return types

IBM Netezza stored procedures are a hybrid between functions and procedures (asdefined by the SQL:2003 standard for SQL-invoked routines). In the Netezzaimplementation, an NZPLSQL stored procedure takes only input arguments andsupports a return value as functions do. Unlike functions, a stored procedure must

1-2 IBM Netezza Stored Procedures Developer's Guide

Page 17: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

be called by using CALL or a similar construct, and it is not allowed in the usualquery locations where a built-in or standard function is allowed.

A stored procedure can also be designed to return a result set. For moreinformation, see “Return a result set” on page 2-25.

How to create and use a stored procedure

As a high-level summary, follow these steps to create and use a stored procedure.These steps are described in more detail in Chapter 3, “Create and manage storedprocedures,” on page 3-11. Design the stored procedure logic and operation.2. Define the stored procedure object by using the CREATE [OR REPLACE]

PROCEDURE command.3. Run or execute the procedure from the SQL command prompt.

As with other IBM Netezza objects, the Netezza admin user can create, list, andexecute stored procedures by default. The admin user can also grant other userspermission to create, list, and execute stored procedures on the Netezza system.Related concepts:“Manage user account permissions” on page 3-1

How to execute a stored procedure

You execute a stored procedure in the SQL command by using either the CALL orEXEC[UTE[ PROCEDURE]] commands. For example, if you have a storedprocedure named updateacct(), you can run it by using any of the followingcommands:MYDB.SCHEMA(USER)=> CALL updateacct();MYDB.SCHEMA(USER)=> EXEC updateacct();MYDB.SCHEMA(USER)=> EXECUTE updateacct();MYDB.SCHEMA(USER)=> EXECUTE PROCEDURE updateacct();

You can also use the SELECT command to execute a procedure; however, youcannot specify a FROM clause. For example:MYDB.SCHEMA(USER)=> SELECT updateacct();

To execute the procedure, the user must be the owner of or have permission toexecute the updateacct() procedure.Related reference:Appendix A, “SQL command reference,” on page A-1

Best practices for stored procedure developersThe following sections describe some best practices for users who develop storedprocedures.

Security considerations

When you define a stored procedure, you can specify whether the IBM Netezzasystem executes the procedure by using the ID of the owner who created the

Chapter 1. Introduction to stored procedures 1-3

Page 18: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

stored procedure or the ID of the user who runs the procedure. The user accountadds an additional layer of security (or expanded access) for the data that isprocessed by the stored procedure.

For example, if the admin user creates a stored procedure and specifies “execute asowner” permission, which is the default, then any user who is allowed to executethe procedure will do so as the admin user. With the admin user privileges, theprocedure could access data in tables or views that the logged-in database usermight not have permission to access. If the user bsmith creates the storedprocedure, then users who can execute the procedure will do so as the user bsmith.

If a procedure should access only the data that the executing user is allowed tosee, define the stored procedure as “execute as caller.” In this case, the procedureuses the user ID of the database user who executes the procedure. The procedurecan access only the data that the calling user is permitted to see.

Cross-database access to stored procedures

When you create a stored procedure by using the CREATE [OR REPLACE]PROCEDURE command, the command adds the procedure to the database andschema to which you are connected. You can access the procedure while connectedto the database where the stored procedure is defined, and you can also runprocedures in other schemas in the same database, or in other databases using thefollowing methods:v Using fully-qualified object names when calling a procedure object that resides

within a different database, for example:MYDB.SCHEMA(ADMIN)=> EXEC OTHERDB.SCHEMA.UPDATEACCT();

v Using a schema.object name when calling a procedure object that resides withina different schema of the same database, for example:MYDB.SCHEMA(ADMIN)=> EXEC SCH_TWO.UPDATEACCT();

v Using the PATH SQL session variable to specify the databases and/or schemasto search to find a procedure name that is not fully qualified. To use the PATHsession variable, you enter a command similar to the following:MYDB.SCHEMA(ADMIN)=> SET PATH = <elem> [, <elem>];

The <elem> value can be a database, a schema, or the variablesCURRENT_CATALOG, CURRENT_USER, CURRENT_SCHEMA, orCURRENT_PATH. Anything you specify as <elem> must resolve to a databasename.For example:MYDB.SCHEMA(ADMIN)=> SET PATH = mydb, nzdb, customer;SET VARIABLE

To display the PATH value, use the following command:MYDB.SCHEMA(ADMIN)=> SELECT CURRENT_PATH;

CURRENT_PATH------------------MYDB,NZDB,CUSTOMER(1 row)

The Netezza system uses the PATH variable during the lookup of any unqualifiedprocedures. It searches the current database if PATH is not set; otherwise itsearches the databases and schemas specified in PATH, in the order that they arespecified. The Netezza system uses the first match that it finds, even if a bettermatch might exist in a subsequent database. A poorer match is one that mightrequire implicit casting of arguments or that causes an error due to multiple

1-4 IBM Netezza Stored Procedures Developer's Guide

Page 19: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

potential matches. Also, the Netezza system uses the PATH session variable to findonly stored procedures, user-defined functions (UDFs), and user-definedaggregates (UDAs). Other object types such as tables, sequences, and so on, are notsupported.

If a stored procedure is invoked from a different database, unqualified objects bindto objects in the invoking database, not in the database where the stored procedureis defined. Unqualified stored procedures, UDFs, and UDAs are exceptions to thisrule because the Netezza system first uses the PATH variable to search for thosethree object types before it searches within the invoking database.

If you plan to invoke cross-database calls to stored procedures that access data inother databases, make sure that the stored procedure uses fully qualified objectnames to refer to those data objects.

Write operations do not work across databases. For any procedures which containinsert, update, delete, create, truncate, alter, or drop commands, make sure thatyou are connected to the database where the stored procedure is defined.

Block quoting supportStored procedures are defined as a block or body of numerous lines of text. IBMNetezza provides a block-quoting mechanism to help ease the definition of theprocedure body and to make the content more readable for debugging andlearning.

A section of text bounded by BEGIN_PROC and END_PROC is a block quote. Thefollowing is an example:CREATE OR REPLACE PROCEDURE name() RETURNS INT4 LANGUAGE NZPLSQL ASBEGIN_PROCDECLARE

string varchar;BEGIN

string := ’This string is quoted’;END;END_PROC;

As shown in the example, quotation marks are not escaped within theblock-quoted string. The string content is always written literally. Backslashes haveno special “escape” meaning.

The stored procedure body is in clear text format by default. Privileged users canuse the SHOW PROCEDURE VERBOSE command and interfaces such asNzAdmin to review the stored procedure. If necessary, you can “hide” theprocedure code when you create the procedure.

Block quotes are intended for use only in NZPLSQL body quoting or storedprocedure invocation. The execution commands CALL and EXEC[UTE[PROCEDURE]] support them, although SELECT does not. They can be used insidea stored procedure body to build DDL statements where they are allowed, but theyhave no quoting implications inside the body. If they are used inside the body,make sure that there are an equal number of both keywords and that they match(a BEGIN_PROC appears before the corresponding END_PROC) to avoid errors. Ifyour program logic dictates that they are not matching, they must be broken up(that is, 'BEGIN_' || 'PROC').

Chapter 1. Introduction to stored procedures 1-5

Page 20: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Both BEGIN_PROC and END_PROC can appear inside a single or double-quotedstring in normal SQL statements if the SQL statements are not inside a block quote.For example:select "BEGIN_PROC" from <table>;insert into <table> values (’BEGIN_PROC’);

If you want to do this inside a block quote body, then you must have a matchingEND_PROC. For example:CREATE OR REPLACE PROCEDURE name() RETURNS INT4 LANGUAGE NZPLSQL ASBEGIN_PROCDECLARE

string varchar;BEGIN

string := ’This string is quoted’;-- This comment is the match for below BEGIN_PROCinsert into va values (’END_PROC’);

END;END_PROC;

Because nested BEGIN_PROC and END_PROC keywords have no quotingimplications, the following example is not supported:CREATE OR REPLACE PROCEDURE name() RETURNS INT4 LANGUAGE NZPLSQL ASBEGIN_PROCDECLARE

string varchar;BEGIN

-- The next statement is a syntax error since it is not quotedstring := BEGIN_PROC This string is not quoted END_PROC;

END;END_PROC;

Related concepts:“Obfuscate the procedure body” on page 3-8

SQL restrictions within the stored procedureWithin the body of a stored procedure, you can use most SQL commands to do thetasks that relate to database objects.

You cannot use SQL commands that are prohibited for use within aBEGIN/COMMIT transaction block within the body of a stored procedure. Startingin release 7.1, you can define a BEGIN AUTOCOMMIT ON block within the body,and within that block you can use all SQL commands, even those prohibited foruse in a BEGIN/COMMIT transaction block such as GENERATE STATISTICS andGROOM TABLE. For more information, see “AUTOCOMMIT ON blocks” on page2-3.

For a description of the transaction control practices and command restrictions, seethe IBM Netezza Database User’s Guide.

Best practices for Netezza administratorsThe following topics describe some best practices for IBM Netezza administratorswho manage Netezza systems that have stored procedures.

Back up and restore stored proceduresAny stored procedures that you create are backed up and restored by the IBMNetezza backup and restore operations. If you back up and restore obfuscatedprocedures, those restored procedures remain obfuscated. If you restore a database

1-6 IBM Netezza Stored Procedures Developer's Guide

Page 21: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

to a system that is running a release which does not support obfuscatedprocedures or VARARGS, for example, those procedures will not run and thequeries that use them will return a syntax error.

If you drop a database, all the objects defined in the database including storedprocedures are likewise dropped. If the Netezza system supports multiple schemasin a database, and you define stored procedures in that schema, dropping theschema will likewise drop all the objects in that schema. As a best practice, youshould keep backup copies of your source CREATE OR REPLACE PROCEDUREdefinitions in a safe location outside of the Netezza system. Make sure that youhave recent backups of your Netezza systems in the event that you need to recoverfrom an accidental deletion or change, or to restore Netezza services as part of adisaster recovery situation.

Upgrade and patch Netezza systems that have storedprocedures

There are no special requirements or procedures necessary to preserve any storedprocedures during an NPS upgrade to a new release. The stored procedurescontinue to operate in the same manner on the upgraded system as on theprevious release.

If the upgrade release introduces any new features or changes that can affect theoperation of stored procedures, Netezza describes the changes in the release notes.Before you install any new release or service pack, review the release notes tofamiliarize yourself with any new features, changes, fixes, and known issues forthat release. Make sure that you have a recent backup of your Netezza systembefore you upgrade the system.

Downgrade Netezza systems that have stored proceduresIf you downgrade your Netezza release, the stored procedures should continue towork after the downgrade. If the downgrade release does not support all theNZPLSQL features of the later release, any procedures that use those features willfail when executed after the downgrade. You can drop or alter those procedures toensure that they conform to the NZPLSQL language support of the Netezza releasethat your system is running.

Chapter 1. Introduction to stored procedures 1-7

Page 22: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

1-8 IBM Netezza Stored Procedures Developer's Guide

Page 23: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Chapter 2. NZPLSQL statements and grammar

This section describes the NZPLSQL language, its structure, and how to use thelanguage to create stored procedures.

NZPLSQL is similar to the Postgres PL/pgSQL language. Some of the languagedescriptions in this section use the Postgres PL/pgSQL documentation. However,NZPLSQL has some differences that are based on the design and environment ofthe IBM Netezza system. NZPLSQL also includes some extensions to assist userswho migrate stored procedures that are written in other languages to the Netezzaenvironment.

NZPLSQL structureThe NZPLSQL language is a block-structured language.

A block is defined as follows:<< label >>[DECLARE

declarations]BEGIN [AUTOCOMMIT ON|OFF]

statementsexception_handlers

END;

You can specify label as an optional way to identify a block in an EXIT statement,or to qualify the names of the variables declared in the block.

The variables declared in the declarations section that precedes a block areinitialized to their default values every time that the block is entered, not just onceper procedure call.

The BEGIN statement specifies the start of a block, or a group of statements,within the body of the procedure. By default, a BEGIN statement operates inAUTOCOMMIT OFF mode, which causes the procedure to execute all thestatements inside the block as one multi-statement transaction. Within the block,you can use most of the SQL commands that you can use at the SQL commandline, but you cannot use the SQL commands that are prohibited for use within aSQL BEGIN/COMMIT transaction block.

Starting in release 7.1, if you specify the BEGIN AUTOCOMMIT ON syntax, theprocedure executes each statement in the block as a singleton statement with animplied COMMIT after each statement. By committing after each statement, theblock adds support for SQL commands that are not allowed with in a BEGIN blocksuch as GROOM TABLE, GENERATE STATISTICS, and the other commands thatare prohibited for use within a BEGIN/COMMIT SQL transaction block. Within aBEGIN/END block, you can specify COMMIT or ROLLBACK commands to eithercommit or roll back all the changes in the current transaction.

Note: The BEGIN/END syntax for grouping statements in NZPLSQL is not thesame as the BEGIN/COMMIT SQL database commands for transaction control.The NZPLSQL BEGIN/END keywords are used only for grouping; they do notstart or end a transaction. Procedures are always executed within a transaction

© Copyright IBM Corp. 2009, 2014 2-1

Page 24: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

established by an outer query; they cannot start or commit transactions, since IBMNetezza SQL does not have nested transactions.

The statements section of a block can contain zero, one, or more sub-blocks. Asub-block is used for logical grouping or to localize variables to a small group ofstatements.

All of the keywords and identifiers are not case-sensitive and can be used in mixeduppercase and lowercase mode. Identifiers are automatically converted touppercase, as they are in general SQL statements, unless they are enclosed inquotation marks to keep them case-sensitive.

The exception_handlers section is an optional section that you can use to catch andprocess an error that occurs in the statements section. If an error does not occur, theexception_handlers section is ignored. For more information, see “Exceptions anderror messages support” on page 2-23.

Transaction commits and rollbacks in stored proceduresThe behavior of a stored procedure depends on whether it is called as a singletonSQL statement or within a SQL transaction block.

When a stored procedure is called as a singleton SQL statement, the changes madeby the stored procedure are committed when the procedure exits or rolled back ifthe procedure aborts.CALL MYPROCEDURE(123);

If the procedure issues a COMMIT or ROLLBACK statement within the procedurebody, all changes made before the transaction statement are committed or rolledback, and the system implicitly starts a new transaction. All statements after thetransaction command continue to run as a single multi-statement command, not asindividual commands inside of a transaction block. When the stored procedureexits, any uncommitted changes are committed or rolled back as they would bewith a stored procedure call before this change.

A sample procedure called test3 follows.CREATE PROCEDURE TEST3()LANGUAGE NZPLSQLRETURNS INT ASBEGIN_PROCBEGIN

statement1;COMMIT;statement2;statement3;RETURN 1234;

END;END_PROC;

Assume that you run the test3 procedure as a singleton SQL statement such asEXECUTE test3(). The procedure executes statement1 and commits that change.The procedure then runs statement2 and statement3, returns the 1234 value, andexits. If the statements complete without error, the statement2 and statement3changes are committed when the procedure exits.

Assume that you run the procedure inside a BEGIN transaction block such as thefollowing example.

2-2 IBM Netezza Stored Procedures Developer's Guide

Page 25: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

BEGIN;execute test3();ROLLBACK;

When you call the test3 procedure within a transaction block, the procedureexecutes statement1 and commits it, then executes statement2 and statement3, butthose statements are not yet committed. The procedure returns control to thetransaction block, which then calls a ROLLBACK command. In this case, thechanges made by statement2 and statement3 are rolled back, but statement1 wasalready committed by the COMMIT statement inside the stored procedure body. Ifthe outside transaction block called a COMMIT instead of a ROLLBACK,statement2 and statement3 would both be committed by transaction blockCOMMIT command.

Remember that if a BEGIN statement starts a transaction block before calling astored procedure, the stored procedure always returns with an active transactionblock, and you must issue a COMMIT or ROLLBACK statement to complete orabort that transaction. Even in the case where an exception causes the storedprocedure to abort, you must still use COMMIT or ROLLBACK after the procedureexits.

AUTOCOMMIT ON blocksEach statement within a stored procedure BEGIN AUTOCOMMIT ON block isexecuted as a singleton statement with an implied commit immediately after thestatement. This behavior is similar to running a series of SQL commands on thecommand line, not inside a BEGIN/COMMIT transaction block.

You can specify all SQL commands inside an AUTOCOMMIT ON block, includingEXECUTE IMMEDIATE, IF statements, FOR statements, and so on. There are norestrictions on the SQL statements. For each statement that is used inside anAUTOCOMMIT ON block, the database changes are automatically committed aftereach statement is executed.

An example of an AUTOCOMMIT block follows.CREATE PROCEDURE TEST4()LANGUAGE NZPLSQLRETURNS BOOLEANBEGIN_PROCBEGIN AUTOCOMMIT ON

GROOM TABLE MYTBL;RETURN TRUE;

EXCEPTION WHEN OTHERS THENRAISE NOTICE 'ERROR: %', SQLERRM;RETURN FALSE;

END;

Note: Executing transactional statements such as COMMIT or ROLLBACK insidean AUTOCOMMIT ON block has no effect because those commands commit orroll back only their own statement. All previous statements are already committed.

There is an implied COMMIT at the beginning of the AUTOCOMMIT ON blockbefore any statement in the block is executed. Any exception that is raised by acommand inside an AUTOCOMMIT ON block calls the exception block, in thesame manner as a normal NZPLSQL statement block.

The behavior of statements in an exception block attached to an AUTOCOMMITON block is based on the AUTOCOMMIT ON/OFF status of the parent block. If

Chapter 2. NZPLSQL statements and grammar 2-3

Page 26: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

an AUTOCOMMIT ON sub-block occurs within an AUTOCOMMIT ON block, thestatements in the exception block are executed as singletons unless you issue aBEGIN within the exception block to change the behavior.

The NZPLSQL language allows statement blocks to be nested within each other.This behavior is supported by AUTOCOMMIT ON blocks as well, so it is possibleto nest AUTOCOMMIT ON|OFF blocks within each other. The syntax BEGINAUTOCOMMIT OFF is the default and is identical to BEGIN without anAUTOCOMMIT clause.BEGIN

Statement1;BEGIN AUTOCOMMIT ON

/* an implicit commit occurs here */Statement2;/* an implicit commit occurs here */Statement3;/* an implicit commit occurs here */

ENDEND;

When an AUTOCOMMIT ON block is nested inside of an AUTOCOMMIT OFFblock, an implicit commit occurs before the first statement is executed inside of theAUTOCOMMIT ON block and then an implicit commit occurs after each statementinside of the AUTOCOMMIT ON block.

When an AUTOCOMMIT OFF block is nested inside of an AUTOCOMMIT ONblock, the statements within the AUTOCOMMIT OFF block are executed as a multistatement transaction that is immediately committed at the end of the block.BEGIN AUTOCOMMIT ON

BEGIN AUTOCOMMIT OFFStatement1;Statement2;

END;/* an implicit commit occurs here */

END;

Exception blocks for an AUTOCOMMIT ON block are executed if any of thestatements within the AUTOCOMMIT ON block fails. Unlike a normal exceptionblock, there is no need to issue a ROLLBACK inside an AUTOCOMMIT ONexception block. The statement that failed is automatically rolled back and a newtransaction is immediately started before processing any statements in theexception block.

CommentsComments within the NZPLSQL language can start with either a double dash or aforward-slash asterisk.v A double dash (--) starts a comment that extends to the end of the line. For

example:-- This is a comment line.

v A forward-slash asterisk pair (/*) starts a block comment, which extends to thenext occurrence of the ending sequence which is an asterisk forward-slash (*/)pair. For example:/* This is a block comment,

which can span multiple lines.Any code inside the block such as:

url varchar := ’http://www.ibm.com’is ignored. */

2-4 IBM Netezza Stored Procedures Developer's Guide

Page 27: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Block comments cannot be nested, but double dash comments can be enclosed in ablock comment. A double dash comment can “hide” the block comment delimiters/* and */.

Variables and constantsAll of the variables, rows, and records that are used in a block or its sub-blocksmust be declared in the declarations section of a block. There are some exceptions,namely the loop variable of a FOR loop that iterates over a range of integer values,and some built-in variables like FOUND, ROW_COUNT, and LAST_OID.

NZPLSQL variables can have any SQL data type, such as INTEGER, VARCHAR,and CHAR. Some sample variable declarations follow:user_id INTEGER;quantity NUMERIC(5,2);url VARCHAR;

A variable declaration has the following syntax:name [ CONSTANT ] type [ NOT NULL ] [ { DEFAULT | := } value ];

v The DEFAULT clause, if included, specifies the initial value assigned to thevariable when the block is entered. If a DEFAULT clause is not specified, thevariable uses the SQL NULL value as its default.

v The CONSTANT option means that the variable cannot be changed; its valueremains constant for the duration of the block.

v If NOT NULL is specified, an assignment of a NULL value results in a runtimeerror. Since the default value of all variables is the SQL NULL value, allvariables declared as NOT NULL must also specify a non-null default value.

When specifying types in declarations, NUMERIC can be specified with or withouta precision and scale. CHAR, NCHAR, VARCHAR, and NVARCHAR can bespecified with or without a size. When these types are specified with a size or aprecision/scale, assignment to the variable follows normal cast rules. If they arespecified without sizes, assignment preserves the original source size orprecision/scale.

The default value is evaluated each time the procedure is called. So assigningnow() to a variable of type timestamp causes the variable to be set to the time ofthe actual procedure call, not the time when the procedure was precompiled intoits bytecode.

Some examples of variable assignments follow:quantity INTEGER := 32;url varchar := ’http://mysite.com’;user_id CONSTANT INTEGER := 10;

By using the %TYPE and %ROWTYPE attributes, you can declare variables withthe same data type or structure of another database item (for example, a tablefield).

The %TYPE attribute provides the data type of a variable or database column. Youcan use this attribute to declare variables that hold database values. For example, ifyou have a column named user_id in your users table, you can declare a variablewith the same data type as user_id as follows:user_id users.user_id%TYPE;

Chapter 2. NZPLSQL statements and grammar 2-5

Page 28: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

By using %TYPE, you do not have to know the data type of the structure that youare referencing. Also, if the data type of the referenced item changes in the future(for example, you change your table definition of user_id to become a REAL), youdo not have to change your procedure definition.

You can declare a row with the structure of a table, as follows:name table%ROWTYPE;

The table value must be an existing table or view name of the database. The fieldsof the row are accessed by using the dot notation.

Only the user attributes of a table row are accessible in the row. You cannot accessan OID or other system attribute because the row could be from a view. The fieldsof the row type inherit the sizes or precision for CHAR, NCHAR, and NUMERICdata types from the table.

Parameter passingIn NZPLSQL, parameters are not named. Instead, only the data types are passed,and parameters are referenced by their position.

To name parameters, use the ALIAS FOR syntax. For example:CREATE OR REPLACE PROCEDURE p1 (int, varchar(ANY)) RETURNS intLANGUAGE NZPLSQL ASBEGIN_PROCDECLARE

pId ALIAS FOR $1;pName ALIAS FOR $2;

BEGININSERT INTO t1 SELECT * FROM t2 WHERE id = pId;

The example highlights the recommended convention to name parameters with a“p” prefix to differentiate them from variables. This convention is helpful becauseparameters are constant and cannot be modified. If a parameter must be updated(for example, to assign it a default value if it is null), assign the parameter to avariable and update the variable. For example:DECLARE

pId ALIAS FOR $1;vID integer;

BEGINvId := ISNULL(pId, 0);INSERT INTO t1 SELECT * FROM t2 WHERE id = vId;

Argument list and variablesThe arguments passed as input to procedures can be identified by using the names$1 (first argument), $2 (second argument), and so on. You can also use the $varnotation, which takes the integer value of var to identify the input value specifiedin that order position.

You can specify 0 - 64 arguments. If you specify VARARGS in the input argumentlist, users can input any number of arguments up to a maximum of 64.

IBM Netezza saves the OIDs of the input arguments in thePROC_ARGUMENT_TYPES array. The array has the same size as the number ofparameters that are passed to the stored procedure. Its elements are of type OIDand contain the OID type of the corresponding input argument. You can use thearray to obtain the number and type of each argument.

2-6 IBM Netezza Stored Procedures Developer's Guide

Page 29: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

For example:CREATE OR REPLACE PROCEDURE test(VARARGS)

RETURNS INT4LANGUAGE NZPLSQLASBEGIN_PROC

DECLAREnum_args int4;typ oid;idx int4;

BEGINnum_args := PROC_ARGUMENT_TYPES.count;RAISE NOTICE ’Number of arguments: %’, num_args;for i IN 0 .. PROC_ARGUMENT_TYPES.count - 1 LOOP

typ := PROC_ARGUMENT_TYPES(i);idx := i+1;RAISE NOTICE ’argument $% is type % and has the value ’’%’’’,

idx, typ, $idx;END LOOP;

END;END_PROC;

A sample call follows:MYDB.SCHEMA(USR2)=> CALL TEST (1, 3, 9::bigint, ’test value’, 324.56);NOTICE: Number of arguments: 5NOTICE: argument $1 is type 23 and has the value ’1’NOTICE: argument $2 is type 23 and has the value ’3’NOTICE: argument $3 is type 20 and has the value ’9’NOTICE: argument $4 is type 705 and has the value ’test value’NOTICE: argument $5 is type 1700 and has the value ’324.56’test------

(1 row)

Related concepts:“Variable arguments” on page 3-7

Scope of variablesWhen you explicitly declare a new variable (or name), the scope of the variable isthe block in which it is defined.

For example, the following sample defines a variable named val in the DECLAREsection of the <<outer>> block, and then defines another val variable in theDECLARE section of the <<inner>> block. Although the variables have the samename, these variables are two different variables:<<outer>>DECLARE

val int4;BEGIN

val := 5;<<inner>>DECLARE

val int4;BEGIN

val := 7;RAISE NOTICE ’inner val != outer val % %’, val, outer.val;

END;RAISE NOTICE ’outer val is 5 %’, val;

END;

Chapter 2. NZPLSQL statements and grammar 2-7

Page 30: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

In this example, the block labels inner and outer can be used to identify a specificval variable by using its fully qualified variable name. If you create this procedureas a stored procedure and run it, you would see output similar to the following:MYDB.SCHEMA(USER)=> call vals();NOTICE: inner val != outer val 7 5NOTICE: outer val is 5 5VALS------

(1 row)

When you declare variables for loop iterators, the iterator variables have their ownunique scope. For example, you can use a variable named val as a loop iterator. Byusing the same sample procedure, this would give you three unique val variablesin your procedure:<<outer>>DECLARE

val int4;BEGIN

val := 5;<<inner>>DECLARE

val int4;BEGIN

val := 7;RAISE NOTICE ’inner val != outer val % %’, val, outer.val;FOR val IN 1 .. 10 LOOP

--Note that this is a NEW val variable for the loop.RAISE NOTICE ’The value of val is %’, val;

END LOOP;RAISE NOTICE ’inner val is still 7. Value %’, inner.val;

END;RAISE NOTICE ’outer val is still 5. Value %’, val;

END;

The following is sample output for this stored procedure:MYDB.SCHEMA(USER)=> call vals();NOTICE: inner val != outer val 7 5NOTICE: The value of val is 1NOTICE: The value of val is 2NOTICE: The value of val is 3NOTICE: The value of val is 4NOTICE: The value of val is 5NOTICE: The value of val is 6NOTICE: The value of val is 7NOTICE: The value of val is 8NOTICE: The value of val is 9NOTICE: The value of val is 10NOTICE: inner val is still 7. Value 7NOTICE: inner val is still 5. Value 5VALS------

(1 row)

As shown in the output, the val variable of the loop iterator has its own scope. Ithas its own value and does not affect the other two val definitions. Within theloop, if you need to call a specific variable that is defined outside the for loop, youcan use the fully qualified form of the variable name (label.variable).Related concepts:“Iterative control” on page 2-19

2-8 IBM Netezza Stored Procedures Developer's Guide

Page 31: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Data types and aliasesThe following table lists the supported data types by their preferred name form,and includes supported aliases and some notes about the values. For moreinformation about the data types and values, see the IBM Netezza Database User’sGuide.

Table 2-1. Supported data types for variables

Data type Alias names Notes

BOOLEAN BOOL A boolean field can store true values, false values, and null. You can usethe following words to specify booleans:

v true or false

v on or off

v ‘0’ or ‘1’

v 'true’ or ‘false’

v ‘t’ or ‘f’

v ‘on’ or ‘off’

v ‘yes’ or ‘no’

CHAR CHARACTER,CHAR(n),CHARACTER(n)

Fixed-length character string, blank padded to length n. If you do notspecify n, the default is an unsized CHAR value. The maximumcharacter string size is 64,000.

VARCHAR CHARACTERVARYING,VARCHAR(n),CHARACTERVARYING(n), CHARVARYING(n)

Variable length character string to a maximum length of n. If you do notspecify n, the default is an unsized VARCHAR value. There is no blankpadding, and the value is stored as entered. The maximum characterstring size is 64,000.

NCHAR NATIONALCHARACTER,NATIONAL CHAR(n),NCHAR(size)

Fixed-length character string, blank padded to length n. If you do notspecify n, the default is an unsized NCHAR value. The maximum lengthis 16,000 characters.

NVARCHAR NATIONALCHARACTERVARYING, NATIONALCHAR VARYING,NATIONAL CHARVARYING(n),NATIONALCHARACTERVARYING(n), andNVARCHAR(n)

Variable length character string to a maximum length of n. If you do notspecify n, the default is an unsized NVARCHAR value. The maximumlength is 16,000 characters.

DATE Specifies a day with resolution that spans January 1, 0001 to December31, 9999 (centered around 2000-01-01).

TIMESTAMP DATETIME Has a date part and a time part, with seconds stored to 6 decimalpositions. The value represents the number of microseconds sincemidnight 2000-01-01.

Min: -63,082,281,600,000,000 (00:00:00, 1/1/0001)

Max: 252,455,615,999,999,999 (23:59:59.999999, 12/31/9999)

TIME TIME WITHOUT TIMEZONE

Hours, minutes, and seconds to 6 decimal positions, ranging from00:00:00.000000 to 23:59:59.999999. This value is microsecond resolutionthat represents the time of day only (midnight to one microsecond beforemidnight).

Chapter 2. NZPLSQL statements and grammar 2-9

Page 32: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Table 2-1. Supported data types for variables (continued)

Data type Alias names Notes

INTERVAL TIMESPAN An interval of time. It has microsecond resolution and ranges from +/-178000000 years. The time part represents everything but months andyears (microseconds) and the month part represents months and years.For more information, see the section on IBM Netezza interval supportin the IBM Netezza Database User’s Guide.

TIME WITHTIME ZONE

TIMETZ Hours, minutes, seconds to 6 decimal positions, and time zone offsetfrom GMT. Ranging from 00:00:00.000000+13:00 to 23:59:59.999999-12:59.

NUMERIC(p,s) NUMERIC, DEC,DEC(p,s),DECIMAL(p,s),DECIMAL

Fixed-point numeric types with precision p and scale s. Precision canrange from 1 to 38, scale from 0 to the precision.

NUMERIC(p) is equivalent to NUMERIC(p,0).

NUMERIC is an unsized numeric value.

Although decimal is sometimes a distinct SQL data type, Netezza SQLtreats it as an alias for NUMERIC.

REAL FLOAT(p), FLOAT4 Floating point number with precision p. Precision values of 1 to 6 areequivalent to FLOAT(6), and are stored as a 4-byte value.

Netezza SQL prefers the type name real, as float(p) is considered more ofan alias for the preferred form.

DOUBLEPRECISION

DOUBLE, FLOAT,FLOAT(p), FLOAT8

Floating point number with precision p, from 7 to 15. Precision values 7 -15 are equivalent to 15 and are stored as an 8-byte value.

Netezza SQL prefers the type name double precision, as float(p) isconsidered more of an alias for the preferred form.

INTEGER INT, INT4 32-bit values in range –2,147,483,648 to 2,147,483,647

BYTEINT INT1 8-bit values in the range –128 to 127

SMALLINT INT2 16-bit values in range –32,768 to 32,767

BIGINT INT8 64-bit values in range -9,223,372,036,854,775,808 to9,223,372,036,854,775,807

Array variablesIn addition to normal scalar variables, NZPLSQL also supports array variables. Todeclare an array variable, use the following syntax:name VARRAY(size) OF type;

All of the elements of the array are initially set to the SQL NULL value for thedeclared type. To assign a value to an element, do the following:name(idx) := value;

This syntax raises an exception if the index (idx) is out of bounds. The followingmethods are supported:name.EXTEND(size)name.COUNTname.TRIM(size)

The EXTEND method extends the array by the specified size. If size is omitted, thedefault is 1.

COUNT returns the number of elements in the array.

2-10 IBM Netezza Stored Procedures Developer's Guide

Page 33: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

TRIM deletes the last size elements in the array (the default is 1). TRIM andEXTEND raise an exception if size is out of bounds.

Array references are allowed almost anywhere variable references are allowed,with the following exceptions:v As an argument to RAISEv As an INTO variablev As the variable in a FOR LOOPv As part of a default value

ExpressionsAll expressions used in NZPLSQL statements are processed by using the backendexecutor.

Expressions that appear to contain constants could require runtime evaluation (forexample, by using 'now()' for the timestamp type) so it is impossible for theNZPLSQL parser to identify real constant values other than the NULL keyword.All expressions are evaluated internally by running a query such as the following:SELECT expression

In the expression, occurrences of variable identifiers are substituted by parametersand the actual values from the variables are passed to the executor in theparameter array. All expressions used in an NZPLSQL procedure are compiled andcached the first time they are encountered. Everything in NZPLSQL is cached,except for variable values and SQL plans. If there is a compile error (syntax error),the expression is not cached. The cached copy is preserved until one of thefollowing happens:v The procedure body is modified.v The procedure is dropped.v The database session ends.

The type checking done by the IBM Netezza SQL main parser has some sideeffects for the interpretation of constant values. For example, the following twoexamples are different in how constant values are interpreted. The first examplefollows:DECLARE

logtxt ALIAS FOR $1;BEGIN

INSERT INTO logtable VALUES (logtxt, ’now()’);RETURN ’now()’;

END;

The second example follows:DECLARE

logtxt ALIAS FOR $1;curtime timestamp;

BEGINcurtime := ’now()’;INSERT INTO logtable VALUES (logtxt, curtime);RETURN curtime;

END

In the first example, when the Netezza SQL main parser prepares the plan for theINSERT, it interprets now() as a timestamp because the target field of logtable is ofthat type. It interprets both instances of now() each time it runs.

Chapter 2. NZPLSQL statements and grammar 2-11

Page 34: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

In the second example, the Netezza SQL main parser does not know what typenow() should become and therefore it returns a data type of text that contains thestring now(). During the assignment to the local variable curtime, the NZPLSQLinterpreter casts this string to the timestamp type by calling the text_out() andtimestamp_in() functions for the conversion.

If record fields are used in expressions or statements, the data types of fieldsshould not change between calls to the same expression or statement.

Literals and math operations in expressionsIf your stored procedures perform math operations in expressions, carefullyconsider the supported ranges for literals and the possible implicit typecasts thatthe IBM Netezza system might perform. These ranges and behaviors can causeunexpected results or overflow errors in complex math expressions.

The Netezza system checks for overflows when performing integer arithmetic. Forexample, all integer literals are 32-bit (signed) numbers by default, which supportsa range of values from -2147483648 to 2147483647. If you perform math operationson a literal, the system checks for and returns an error if it detects an overflow. Forexample, the following stored procedure defines a numeric value n, assigns it thelargest supported value (2147483647) and then adds 1 to the value:CREATE OR REPLACE PROCEDURE num() RETURNS BOOL LANGUAGE NZPLSQL ASBEGIN_PROCDECLAREn NUMERIC;BEGINn := 2147483647;RAISE NOTICE ’n is %’, n;n := 2147483647 + 1;RAISE NOTICE ’n is %’, n;END;END_PROC;

If you create and run this stored procedure, the procedure fails and returns aninteger overflow error:NOTICE: n is 2147483647NOTICE: Error occurred while executing PL/pgSQL function NUMNOTICE: line 6 at assignmentERROR: overflow in 32 bit arithmetic

To avoid an overflow condition, you can use a cast operation to cast n to a higherprecision type, or assign values to intermediate values. For example, the followingstored procedure creates the overflow issue for the numeric value n but uses caststo numerics or bigints to increase the range of valid values:CREATE OR REPLACE PROCEDURE num() RETURNS BOOL LANGUAGE NZPLSQL ASBEGIN_PROCDECLAREn NUMERIC;BEGIN

n := 2147483647;RAISE NOTICE ’n is %’, n;n := 2147483647::numeric + 1;RAISE NOTICE ’n is %’, n;n := 2147483647::bigint + 1;RAISE NOTICE ’n is %’, n;

END;END_PROC;

2-12 IBM Netezza Stored Procedures Developer's Guide

Page 35: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

If you create and run this stored procedure, the output would be similar to thefollowing:NOTICE: n is 2147483647NOTICE: n is 2147483648NOTICE: n is 2147483648

As this example shows, explicit casts during arithmetic evaluations and careful useof literals, constants, and types can help to increase the accuracy of the expressionsused in your stored procedures.

If you use floating point numbers in expressions, Netezza attempts to cast it into anumeric if possible, with a specific precision and scale that it calculates withinternally defined casting rules.

Because arithmetic operations in a stored procedure are evaluated by invoking thebackend executor, they are processed as SELECT statements. To more clearly seethe calculated shape of the expression result, it can be helpful to use it to create atable, which can then be described by using the \d command. Printing the resultsmight not provide enough insight to the resulting data types.

In the arithmetic expression that follows, Netezza casts the precision and scalebased on internal Netezza SQL behavior rules:DEV.SCH1(ADMIN)=> create table test as select (1 + 0.08/365) interest;INSERT 0 1DEV.SCH1(ADMIN)=> \d test

Table "TEST"Attribute | Type | Modifier | Default Value----------+--------------+----------+---------------INTEREST | NUMERIC(8,6) | |Distributed on hash: "INTEREST"

In the sample table, the Netezza internal casting rules evaluated the expression“1+0.08/365” and determined that the field would be a numeric value with 8digits of precision and 6 digits of scale. The following command shows the actualvalue saved in the row:DEV.SCH1(ADMIN)=> select * from TEST;INTEREST----------1.000219(1 row)

Another example follows:DEV.SCH1(ADMIN)=> create table test2 as select (4 + 1/5) loanrt;INSERT 0 1DEV.SCH1(ADMIN)=> \d test2

Table "TEST2"Attribute | Type | Modifier | Default Value----------+----------+----------+---------------LOANRT | INTEGER | |Distributed on hash: "LOANRT"

In the previous example, Netezza is evaluating three integer values (4, 1, and 5).The Netezza system uses integer as the type for the new column. If you displaythe column value, as follows, you can see that the “decimal” portion of the valuewas truncated:

Chapter 2. NZPLSQL statements and grammar 2-13

Page 36: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

DEV.SCH1(ADMIN)=> select * from TEST2;LOANRT--------

4(1 row)

A similar example follows, but instead of the expression 1/2, this expression usesthe numeric value .5 instead, as follows:DEV.SCH1(ADMIN)=> create table test3 as select (4 + .5) loanrt;INSERT 0 1DEV.SCH1(ADMIN)=> \d test3

Table "TEST3"Attribute | Type | Modifier | Default Value----------+---------------+----------+---------------LOANRT | NUMERIC(3,1) | |Distributed on hash: "LOANRT"DEV.SCH1(ADMIN)=> select * from TEST3;LOANRT--------

4.5(1 row)

In this example, the .5 value is interpreted as 0.5, and thus cast to numeric(3,1).

In addition to the casts that can occur when math expressions are parsed, Netezzafunctions can also cause an implicit typecast. For example, the function sqrt()takes and returns a double precision value. The following example uses thefunction to define a table column:DEV.SCH1(ADMIN)=> create table test4 as select (sqrt(42));INSERT 0 1DEV.SCH1(ADMIN)=> \d test4

Table "TEST4"Attribute | Type | Modifier | Default Value----------+------------------+----------+---------------SQRT | DOUBLE PRECISION | |Distributed on hash: "SQRT"DEV.SCH1(ADMIN)=> select * from TEST4;

SQRT-----------------6.4807406984079(1 row)

In the test4 example, the sqrt() function causes Netezza to cast the input integervalue to a double and to return a double.

Remember these behaviors when you work with stored procedures that usearithmetic expressions to evaluate data. The implicit casts might not provide thevalue that you would expect if you evaluated the same arithmetic expression witha calculator. An example follows:CREATE OR REPLACE PROCEDURE sp_expressions_numeric02() RETURNS NUMERICLANGUAGE NZPLSQL ASBEGIN_PROC

DECLAREthisnum9_2 NUMERIC(9,2);million NUMERIC(9,2) := 1000000.00;thisnum18 NUMERIC(18);litespeed NUMERIC := 186282;thisnum38 NUMERIC(38);

BEGIN/* The following expression causes implicit casts in the math

evaluation, reducing the precision and scale of the result. */thisnum9_2 := million * (1 + 0.08/365)^(365 * 20);

2-14 IBM Netezza Stored Procedures Developer's Guide

Page 37: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

RAISE NOTICE ’thisnum9_2 == %’, thisnum9_2;

/* The following expression uses an explicit cast to increasethe precision and scale of the intermediate evaluation. */

thisnum9_2 := million * (1 + 0.08::numeric(20,15)/365)^(365 * 20);RAISE NOTICE ’thisnum9_2 == %’, thisnum9_2;

/* The following expression uses the numeric literal litespeed toconvert the speed of light from miles per sec to miles peryear. */

thisnum18 := litespeed * 60 * 60 * 24 * 365.25;RAISE NOTICE ’thisnum18 == %’, thisnum18;/* The following expression uses the integer 186282 to convert

lightspeed from miles per sec to miles per year. In theright-side evaluation, however, the values overflowed theupper limit of an int several times during evaluation,which causes an overflow error. */

thisnum38 := 186282 * 60 * 60 * 24 * 365.25;RAISE NOTICE ’thisnum38 == %’, thisnum38;

END;END_PROC;

Sample output follows:NOTICE: thisnum9_2 == 4945731.93NOTICE: thisnum9_2 == 4952164.15NOTICE: thisnum18 == 5878612843200NOTICE: Error occurred while executing PL/pgSQL function SP_EXPRESSIONS_NUMERIC02NOTICE: line 16 at assignmentERROR: overflow in 32 bit arithmetic

StatementsThis section describes the types of statements that are explicitly understood by theNZPLSQL parser. Any statements that are not specified by using these conventions(and thus are not understood by the NZPLSQL parser) are assumed to be SQLcommands and sent to the database engine to execute. The resulting query shouldnot return any data.

AssignmentTo assign a value to a variable or row/record field, use the assignment statementas follows:identifier := expression;

If the expression’s result data type does not match the variable’s data type but thetypes are compatible, or the variable has a size/precision that is known (as forchar(20)), the result value is implicitly cast by the NZPLSQL bytecode interpreterusing the result type’s output-function and the variable’s type input-function. Notethat this could potentially result in runtime errors generated by the type’s inputfunctions.

Several examples follow:user_id := 20;tax := subtotal * 0.06;

For more information about IBM Netezza casting rules and behaviors, see the IBMNetezza Database User’s Guide.

Chapter 2. NZPLSQL statements and grammar 2-15

Page 38: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Call another procedureAll procedures defined in an IBM Netezza database return a value; the defaultvalue is NULL. Thus, the normal way to call a procedure is to run a SELECTquery or to do an assignment (resulting in an NZPLSQL internal SELECT).

However, there are cases where you might not be concerned with the result of theprocedure. In these cases, use the CALL statement to call the procedure, as follows:CALL query

The CALL statement runs a SELECT query and discards the result. Identifiers suchas local variables are still substituted into input parameters.

There is a maximum stored procedure call recursion limit of 1024. If the callrecursion exceeds this value, the following error message is returned:ERROR: stored procedure recursion limit exceeded

Run dynamic queriesThere might be times when you want to generate dynamic queries inside yourNZPLSQL procedures. Or, you might have procedures that are designed togenerate other procedures. For these situations, NZPLSQL provides the EXECUTEIMMEDIATE statement:EXECUTE IMMEDIATE query-string

The query-string value is a string of type text which contains the query to beexecuted.

When working with dynamic queries, make sure that you escape any quotationmarks in NZPLSQL.

A query run by an EXECUTE IMMEDIATE statement is prepared each time thestatement is run. The query string can be dynamically created within the procedureto do actions on different tables and fields.

The results from SELECT queries are discarded by EXECUTE IMMEDIATE, andSELECT INTO is not currently supported within EXECUTE IMMEDIATE. So, theonly way to extract a result from a dynamically created SELECT is to use the FOR... EXECUTE form, described in “Iterate through the records of a query” on page2-21.

An example statement follows:EXECUTE IMMEDIATE ’UPDATE tbl SET’|| quote_ident(’fieldname’)|| ’ = ’|| quote_literal(’newvalue’)|| ’ WHERE ...’;

This example demonstrates the use of the quote_ident and quote_literalfunctions. To ensure that strings are correctly processed for quotation marks orspecial characters, expressions that contain column and table identifiers should bepassed to quote_ident. Expressions containing values that are literal strings in theconstructed command should be passed to quote_literal. Both take theappropriate steps to return the input text enclosed in double quotation marks forquote_ident or quotation marks for quote_literal with any embedded specialcharacters properly escaped.

2-16 IBM Netezza Stored Procedures Developer's Guide

Page 39: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Obtain other results statusThere are two variables that provide system status indicators: ROW_COUNT andLAST_OID.v ROW_COUNT is the number of rows processed by the last SQL query sent

down to the SQL engine.v LAST_OID is the object ID (oid) of the last row inserted by the most recent SQL

query.

LAST_OID is useful only after an INSERT query, and then only when the inserthappens on a catalog table. In practice, LAST_OID is not likely to be useful.

In addition to these variables, you can also use the FOUND and IS NULL variablesto do special conditional processing based on record results.Related concepts:“Assignments” on page 2-20

Return from a procedureUse the RETURN command to return data from a procedure.RETURN [expression]

The procedure terminates and the value of expression is returned to the upperexecutor. If expression is not provided, NULL is assumed.

The return value of a procedure can be undefined. If control reaches the end of thetop-level block of the procedure without encountering a RETURN statement,NULL is assumed. The result of the expression is automatically cast into the returntype of the procedure as described for assignments.

Control StructuresControl structures are a useful and important part of the NZPLSQL language. Youcan use NZPLSQL control structures to manipulate SQL data in a flexible andpowerful way.

Conditional controlYou use IF statements to take action based on certain conditions. NZPLSQL hasthree forms of IF statements:v IF-THENv IF-THEN-ELSEv IF-THEN-ELSE IF

All NZPLSQL IF statements require a corresponding END IF statement. In ELSE-IFstatements, you need two END IF statements: one for the first IF and one for thesecond (ELSE IF).

IF-THEN statements

IF-THEN statements are the simplest form of an IF statement. The statementsbetween THEN and END IF are executed if the condition is true. Otherwise, thestatements that follow the END IF are executed. An example follows:IF v_user_id <> 0 THEN

UPDATE users SET email = v_email WHERE user_id = v_user_id;END IF;

Chapter 2. NZPLSQL statements and grammar 2-17

Page 40: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

IF-THEN-ELSE statements

IF-THEN-ELSE statements add an ELSE branch for cases when the IF-THENcondition evaluates to FALSE. You can specify the statements to run in the ELSEsection. For example:IF parentid IS NULL or parentid = ’’THEN

return fullname;ELSE

return hp_true_filename(parentid) || ’/’ || fullname;END IF;

IF v_count > 0 THENINSERT INTO users_count(count) VALUES(v_count);return ’t’;

ELSEreturn ’f’;

END IF;

You can nest IF statements as in the following example:IF movies.genre = ’d’ THEN

film_genre := ’drama’;ELSE

IF movies.genre = ’c’ THENfilm_genre := ’comedy’;

END IF;END IF;

IF-THEN-ELSE IF statements

When you use the "ELSE IF" statement, you are nesting an IF statement inside theELSE statement. Thus, you need one END IF statement for each nested IF and onefor the parent IF-ELSE. For example:IF movies.genre = ’d’ THEN

film_genre := ’drama’;ELSE IF movies.genre = ’c’ THEN

film_genre := ’comedy’;END IF;

END IF;

While this form works, it can become a little tedious and error-prone if there aremany alternatives to check. Thus, the language offers the alternative syntax byusing ELSIF or ELSEIF, as follows:IF movies.genre = ’d’ THEN

film_genre := ’drama’;ELSIF movies.genre = ’c’ THEN

film_genre := ’comedy’;ELSIF movies.genre = ’a’ THEN

film_genre := ’action’;ELSIF movies.genre = ’n’ THEN

film_genre := ’narrative’;ELSE-- An uncategorized genre form has been requested.

film_genre := ’Uncategorized’;END IF;

The IF-THEN-ELSIF-ELSE form offers some flexibility and eases the coding processwhen you need to check many alternatives in one statement. While it is equivalentto nested IF-THEN-ELSE-IF-THEN commands, it needs only one END IFstatement.

2-18 IBM Netezza Stored Procedures Developer's Guide

Page 41: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Iterative controlWith the LOOP, WHILE, FOR, and EXIT statements, you can control the flow ofexecution of your NZPLSQL program iteratively.

LOOP statement

The LOOP statement defines an unconditional loop that repeats until terminatedby an EXIT statement or a RETURN statement (which terminates the procedureand the loop). It has the following syntax:[<<label>>]LOOP

statementsEND LOOP;

The optional label can be used by EXIT statements of nested loops to specify whichlevel of nesting is terminated.

EXIT statement

The EXIT statement terminates a loop. It has the following syntax:EXIT [ label ] [ WHEN expression ];

If you do not specify a label, the innermost loop is terminated and the statementthat follows END LOOP runs next. If you specify a label, it must be the label ofthe current or an upper level of nested loop or blocks. Then the named loop orblock is terminated and control continues with the statement after thecorresponding END of the loop or blocks.

Examples:LOOP-- some computationsIF count > 0 THENEXIT; -- exit loopEND IF;END LOOP;

LOOP-- some computationsEXIT WHEN count > 0;END LOOP;

BEGIN-- some computationsIF stocks > 100000 THENEXIT;END IF;END;

WHILE statement

With the WHILE statement, you can loop through a sequence of statements if theevaluation of the condition expression is true.[<<label>>]WHILE expression LOOPstatementsEND LOOP;

For example:

Chapter 2. NZPLSQL statements and grammar 2-19

Page 42: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP-- some computations hereEND LOOP;

WHILE NOT boolean_expression LOOP-- some computations hereEND LOOP;

FOR statement

By using the FOR statement, you can create a loop that iterates over a range ofinteger values.[<<label>>]FOR name IN [ REVERSE ] expression .. expression LOOPstatementsEND LOOP;

The variable name is automatically created as type integer and exists only insidethe loop. The two expressions for the lower and upper bound of the range areevaluated only when entering the loop. The iteration step is always 1.

Some examples of FOR loops:FOR i IN 1 .. 10 LOOP-- some expressions hereRAISE NOTICE ’i is %’,i;END LOOP;

FOR i IN REVERSE 10 .. 1 LOOP-- some expressions hereEND LOOP;

Related concepts:“Scope of variables” on page 2-7

RecordsRecords are similar to row types, but they have no predefined structure. They areused in selections and FOR loops to hold one database row from a SELECToperation.

DeclarationVariables of type RECORD can be used for different selections. Accessing a recordor an attempt to assign a value to a record field when there is no row in it resultsin a runtime error. To declare a RECORD variable:name RECORD;

AssignmentsYou can use the following query to assign a complete selection into a record orrow:SELECT expressions INTO target FROM ...;

The target value can be a record, a row variable, or a comma-separated list ofvariables and record-fields or row-fields. This interpretation is different from theSQL interpretation of SELECT INTO, which is that the INTO target is a newlycreated table. (If you want to create a table from a SELECT result inside anNZPLSQL procedure, use the equivalent syntax CREATE TABLE AS SELECT.)

2-20 IBM Netezza Stored Procedures Developer's Guide

Page 43: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

If a row or a variable list is used as the target, the selected values must exactlymatch the structure of the target or targets, or a runtime error occurs. The FROMkeyword can be followed by any valid qualification, grouping, or sorting that canbe given for a SELECT statement.

After a record or row is assigned to a RECORD variable, you can use the "." (dot)notation to access fields in that record as follows:DECLARE

users_rec RECORD;full_name varchar;

BEGINSELECT * INTO users_rec FROM users WHERE user_id=3;

full_name := users_rec.first_name || ’ ’ || users_rec.last_name;

There is a special variable named FOUND of type boolean that can be usedimmediately after a SELECT INTO to check whether an assignment was successful.The following example uses the NOT FOUND form to raise an exception if aSELECT INTO statement does not match on the requested input name:SELECT * INTO myrec FROM EMP WHERE empname = myname;IF NOT FOUND THEN

RAISE EXCEPTION ’employee % not found’, myname;END IF;

FOUND is very similar to ROW_COUNT. For example, the following statement:IF FOUND

is equivalent to this statement:IF ROW_COUNT >= 1

You can also use the IS NULL (or ISNULL) conditionals to test whether a RECORDor ROW is NULL. If the selection returns multiple rows, only the first is movedinto the target fields. All others are silently discarded. For example:DECLARE

users_rec RECORD;full_name varchar;

BEGINSELECT * INTO users_rec FROM users WHERE user_id=3;IF users_rec.homepage IS NULL THEN

-- user entered no homepage, return "http://"return ’http://’;

END IF;END;

Related concepts:“Obtain other results status” on page 2-17

Iterate through the records of a queryBy using a special type of FOR loop, you can iterate through the results of a queryand manipulate that data. The FOR IN loop syntax is as follows:[<<label>>]FOR record | row IN select_clause LOOP

statementsEND LOOP;

The record or row is assigned all the rows that result from the select clause and theloop body runs for each. An example follows:

Chapter 2. NZPLSQL statements and grammar 2-21

Page 44: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

DECLAREmviews RECORD;-- Instead, if you did:-- mviews cs_materialized_views%ROWTYPE;-- this record is ONLY usable for the cs_materialized_views table

BEGINCALL cs_log(’Refreshing materialized views...’);FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP-- Now "mviews" has one record from cs_materialized_views

RAISE EXCEPTION, ’Can’t execute SQL while processing SQL for %’,mview.my_name;

END LOOP;CALL cs_log(’Done refreshing materialized views.’);return 1;

end;

If the loop is terminated with an EXIT statement, the last assigned row is stillaccessible after the loop.

The FOR-IN EXECUTE statement is another way to iterate over records:[<<label>>]FOR record | row IN EXECUTE text_expression LOOP

statementsEND LOOP;

This form is similar to the previous form, except that the source SELECT statementis specified as a string expression. The main difference between the two is thesyntax and use of variables to build the SQL to run. The first form is faster toevaluate.

Report messages and raise errorsUse the RAISE statement to report messages and raise errors.

The statement syntax follows:RAISE level ’format’ [, identifier [...]];

Inside format, the percent character (%) is used as a placeholder for a subsequent,comma-separated identifier. You can specify more than one % and identifier pair,as follows:RAISE NOTICE ’Welcome % %’, firstname, lastname;

In this example, the notice message substitutes the value of firstname for the first% character, and substitutes the value of lastname for the second % character.

The message levels are as follows:v DEBUG messages are written only to pg.log.v NOTICE messages are written to the database log and forwarded to the client

application.v EXCEPTION messages are written to the database log, forwarded to the client

application as non-fatal messages, and usually abort the transaction if they arenot caught.

The following is an example of a RAISE statement:RAISE NOTICE ’Calling cs_create_job(%)’, job_id;

2-22 IBM Netezza Stored Procedures Developer's Guide

Page 45: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

In the example, job_id replaces the % in the string and display the message to theclient and in pg.log.RAISE EXCEPTION ’Inexistent ID --> %’, user_id;

This EXCEPTION statement aborts the transaction (if the exception is not caught)and writes the message to the database log.

Exceptions and error messages supportAny error that occurs in an NZPLSQL procedure aborts the execution of theprocedure, and it aborts the surrounding transaction as well. The system returns tothe main loop to obtain the next query from the client application. It is not possibleto catch all exceptions, especially if that action leaves the database in a bad state.

To catch and process an error that occurs in a procedure block, you can add anexception-handling section at the end of a block by using the EXCEPTIONkeyword. If no error occurs, the exception-handling section is ignored. Within theexception-handling section, you can specify one or more exception handlers byusing WHEN clauses that specify the exception to match and the statements to runwhen a match occurs. An EXCEPTION statement has the following form:EXCEPTION

WHEN clause THENstatements

[ WHEN ... ]

The NZPLSQL supports two clauses for exception processing:

TRANSACTION_ABORTEDUse the TRANSACTION_ABORTED clause to specify the statements thatyou want to run when an error occurs that causes the transaction to abort.In this case, a ROLLBACK is required to continue. Make sure that theROLLBACK command is the first command in the exception handlingstatements.

OTHERSUse the OTHERS clause to specify the statements to run when any erroroccurs within the procedure block. Errors such as a SQL parsing error donot abort the transaction, and thus would not match aTRANSACTION_ABORTED clause.

You can specify both clauses in an exception block, as in the following example.When an error occurs in the procedure, the procedure code uses the first matchingexception clause and executes the statements in that clause. Any clauses after thematch are ignored. As a best practice, specify the OTHERS clause last because itmatches any type of error.EXCEPTION

WHEN TRANSACTION_ABORTED THENROLLBACK;statements_case1RAISE ERROR ’Procedure failed: %’, sqlerrm;

WHEN OTHERS THENstatements_case2RAISE NOTICE ’Caught error, continuing %’, sqlerrm;

In this example, an error that aborts a transaction triggers theTRANSACTION_ABORTED clause and the stored procedure executes theROLLBACK, the statements in statements_case1, and raises the error message. Ifthe error did not cause the transaction to abort, the exception processing skips to

Chapter 2. NZPLSQL statements and grammar 2-23

Page 46: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

the OTHERS clause and the stored procedure runs the statements_case2 set andraises the notice message. If there were no errors in the block, the exceptionstatements are skipped.

The variable SQLERRM contains the text of an error message that is caught. In theabsence of an exception block, the exception propagates up to the next storedprocedure in the call stack. If sproc1 calls sproc2, which generates an exception,but sproc2 does not have an exception handler, then the system looks for a handlerin sproc1. The system also looks at the enclosing block declarations.

For example:create or replace procedure sp_except01() returns BOOL LANGUAGENZPLSQL ASBEGIN_PROCDECLARE

r record;BEGIN

<<inner>>BEGIN

SELECT * INTO r FROM NONEXISTENT;END;

END;END_PROC;

create or replace procedure sp_except02() returns BOOL LANGUAGENZPLSQL ASBEGIN_PROCBEGIN

CALL sp_except01();END;END_PROC;

create or replace procedure sp_except03() returns BOOL LANGUAGENZPLSQL ASBEGIN_PROCBEGIN

CALL sp_except02();EXCEPTION WHEN OTHERS THEN

RAISE NOTICE ’Caught exception’;END;END_PROC;

In these examples, the exception is generated in sp_except01, in the block inner.The system first checks for an exception handler for block inner, which is notfound. Control passes to the parent context, which is the procedure sp_except01,and an exception handler is also not found there. Control then passes tosp_except02, and finally sp_except03, where an exception handler is found andused.

If an exception is not caught at any level, additional NOTICE-level log messagesare sent to provide context about the error and where it occurred (line number andtype of statement, unless the error is from a RAISE EXCEPTION statement).

If you include exception handlers in stored procedures, the handlers catch anyerrors and the errors are not displayed. For example:CREATE PROCEDURE sp() RETURNS INTEGER LANGUAGE NZPLSQL ASBEGIN_PROCBEGIN

2-24 IBM Netezza Stored Procedures Developer's Guide

Page 47: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

EXECUTE IMMEDIATE ’insert into NOTEXIST’ || ’values(1,1)’;EXCEPTION WHEN OTHERS THENEND;

END_PROC;

Assuming that NOTEXIST does not exist in the database, the query does notdisplay any error output because the error was handled by the exception handler.

To display the error, write the procedure as follows:CREATE PROCEDURE sp() RETURNS INTEGER LANGUAGE NZPLSQL ASBEGIN_PROCBEGIN

EXECUTE IMMEDIATE ’insert into NOTEXIST’ || ’ values(1,1)’;EXCEPTION WHEN OTHERS THEN

RAISE NOTICE ’Got exception: %’, SQLERRM;END;

END_PROC;

When you run this query, it displays the following output:NOTICE: Got exception: ERROR: Relation ’NOTEXIST’ does not exist

Return a result setTypically, an NZPLSQL procedure returns a unique return value, but it can alsoreturn a result set in the form of a specified table.

To create a stored procedure that returns a result set:v Define the stored procedure with a return value of “RETURNS REFTABLE

(<table-name>)” to indicate that it returns a result set that looks like thespecified table.

v Inside the body of the procedure, use the variable REFTABLENAME to refer tothe results table.

The table specified in the RETURNS value must exist at the time that the storedprocedure is created, although the table can be empty. The table continues to existafter the stored procedure completes. You cannot drop the reference table while thestored procedure is defined. (That is, you must drop the stored procedure ormodify it to return a different reference table before you can drop the table.)

For example, the following stored procedure, returntwo, returns a result set byusing the reference table feature. The reference table that it uses, tbl, waspreviously defined by using the following command:CREATE TABLE tbl (i INT4, i2 bigint);

A description of tbl follows:DEV.SCH1(ADMIN)=> \d tbl

Table "TBL"Attribute | Type | Modifier | Default Value-----------+---------+----------+---------------I | INTEGER | |I2 | BIGINT | |Distributed on hash: "I"

After you confirm that the reference table exists, you can use the followingcommand to define the stored procedure returntwo:DEV.SCH1(ADMIN)=> CREATE OR REPLACE PROCEDURE returntwo(timestamp) RETURNSREFTABLE(tbl) LANGUAGE NZPLSQL ASBEGIN_PROC

Chapter 2. NZPLSQL statements and grammar 2-25

Page 48: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

BEGINEXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (1,1)’;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (2,2)’;RETURN REFTABLE;

END;END_PROC;

A sample call to the returntwo stored procedure follows:DEV.SCH1(ADMIN)=> EXECUTE PROCEDURE returntwo(now());I | I2---+----1 | 12 | 2(2 rows)

Restriction: You cannot specify a WHERE clause in a query that calls a storedprocedure that returns a result set.

When you call or invoke the stored procedure by using a SQL command such asSELECT procedure(), CALL procedure(), EXECUTE procedure(), and so on, thedatabase does the following:v Generates a table name TEMPFUNC<oid> where oid is the object ID of the

procedure that was invokedv Checks if the table name exists; if it does, it issues a DROP TABLE

<temp-table-name> commandv Issues a CREATE TEMPORARY TABLE <temp-table-name> as select * from

<table-name> LIMIT 0 to create the table for the results set with no initialcontents

v Returns the results of SELECT * from <temp-table-name> where proc(args) isNULL (This situation is the only situation in which a stored procedure isallowed to be invoked with a FROM clause and where the return value is usedas part of a query.)

To use this in a procedure, you must insert your results in <temp-table-name> byusing the REFTABLENAME variable to obtain the name. This SQL command mustbe invoked dynamically to use the variable.

Additionally, you must return NULL in your procedure by one of the followingmeans:v RETURN REFTABLE;v RETURN NULL;v RETURN;v Not specifying a RETURN clause.

If you do not return NULL, the procedure returns an error. The recommendedmethod to return NULL is RETURN REFTABLE.

One REFTABLE procedure can call another, but you encounter unusual results if aREFTABLE procedure calls itself (either directly or recursively) because of thetemporary table logic; therefore, avoid designing a REFTABLE procedure whichcalls itself.

Cross-database access for a REFTABLE procedure should work without problem asthe temporary table will be created in the local database; it will retrieve the shapeof the REFTABLE definition in the other database.

2-26 IBM Netezza Stored Procedures Developer's Guide

Page 49: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

The SQL that is executed (for example, CREATE TEMPORARY TABLE, DROPTABLE) uses the owner ID of the procedure as the effective user ID if EXECUTEAS OWNER is set; otherwise, if EXECUTE AS CALLER is set, the SQL uses theuser ID of the account which calls or invokes the procedure.

REFTABLE and ROLLBACK commandsIf a stored procedure returns a result set (REFTABLE), do not issue a ROLLBACKcommand inside the procedure body unless you first issue a COMMIT to createthe temporary table for REFTABLE. Issuing a ROLLBACK without the priorCOMMIT command causes your REFTABLE procedure to fail when executed.

As a best practice, if your procedure body includes a ROLLBACK command, or ifyou call another procedure that could issue a ROLLBACK, specify the COMMITcommand as the first statement in the REFTABLE procedure body. An examplefollows:DEV.SCH1(ADMIN)=> CREATE OR REPLACE PROCEDURE returntwo(timestamp) RETURNSREFTABLE(tbl) LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINCOMMIT;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (1,1)’;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (2,2)’;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (3,3)’;COMMIT;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (4,4)’;ROLLBACKRETURN REFTABLE;

END;END_PROC;

DEV.SCH1(ADMIN)=> EXECUTE returntwo(now());I | I2---+----2 | 21 | 13 | 3(3 rows)

As shown in the example, your procedure can call the COMMIT command asneeded, but the first COMMIT ensures that the temporary table exists forprocessing within the body.

The following message is an example of the error that occurs when theROLLBACK ran without a prior COMMIT:DEV.SCH1(ADMIN)=> EXECUTE returntwo(now());NOTICE: Error occurred while executing PL/pgSQL function RETURNTWONOTICE: line 1 at SQL statementERROR: Cannot use ROLLBACK from within a stored procedure which usesa REFTABLE without a COMMIT first.

Manage large data setsIf users run stored procedures on large data sets, there might be situations wherethere is not enough memory to hold the results of a select on that table. Forexample, some stored procedures can read each record from a table and take actionon each record:

Chapter 2. NZPLSQL statements and grammar 2-27

Page 50: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

FOR rec in SELECT * from tablenm LOOP

--perform processing steps

END LOOP:

The SELECT operation runs first and caches its results in memory or as atemporary file on disk, depending upon the size of the result set. The procedurethen applies the steps in the inner processing loop.

If the table (tablenm) is very large, such as a table with millions of rows or onewith many thousands of large rows, the temporary file can be a huge file that usesthe free disk space on the IBM Netezza host. Use caution when your storedprocedures process very large tables.

Note: In the Netezza environment, these types of select loops that operate onsingle rows are not optimized for performance in the Netezza environment. Wherepossible, recast the loop to operate on record sets.Related concepts:“Tips and best practices for stored procedures”

Advanced development topicsThis section describes some topics that show how you can take advantage ofuser-defined functions and stored procedures to perform advanced programmingand scripting on the Netezza system.

Extend the NZPLSQL language with UDFsIf you or other users at your site create user-defined functions (UDFs) for yourIBM Netezza systems, you can use UDFs to extend the NZPLSQL language. TheseUDFs must be invoked by using SQL that is designed to run only on the Netezzahost inside Postgres. For details about the use of UDFs to extend NZPLSQL, seethe IBM Netezza User-Defined Functions Developer’s Guide.

Tips and best practices for stored proceduresThis section describes some common tips and best practices for stored procedures.

Control-C interrupt processing in loops

If the procedure encounters an infinite loop, you can press Control-C to interruptthe loop. This key sequence should cause an exception (which is not catchable) andthus cause the loop and the procedure call to be interrupted and return.

Query processing in loops

Within stored procedures, there can be loop designs that appear to use concurrentqueries to process the results. For example, the following procedure uses a SELECTto gather information, which is then processed for a possible DELETE action:FOR rec in SELECT * from mytable LOOP

IF rec.type = 'd' THENEXECUTE IMMEDIATE 'DELETE FROM mytable2 WHERE recid = ' || rec.id;

END IF;END LOOP;

While it appears that the outer FOR loop SELECT and the inner EXECUTEIMMEDIATE queries are running at the same time, the SELECT query finishes and

2-28 IBM Netezza Stored Procedures Developer's Guide

Page 51: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

caches its results before the inner query begins. Thus, deleting records from thetable in the inner loop does not affect the SELECT query in the outer loop orchange its results.

Note: Although it can be common to run row-at-a-time operations, as used in thepreceding example, you can significantly improve the performance of theseprocedures by designing them to operate on sets of records rather than single rowoperations. For example, if you recast the previous example to the following:DELETE from mytable2 where recid in (select recid from my tablewhere type = ’d’) ;

This procedure design can take advantage of the IBM Netezza massively parallelprocessing (MPP) environment to run much quicker.Related concepts:“Manage large data sets” on page 2-27

Chapter 2. NZPLSQL statements and grammar 2-29

Page 52: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

2-30 IBM Netezza Stored Procedures Developer's Guide

Page 53: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Chapter 3. Create and manage stored procedures

This section describes the basic management and user tasks associated with storedprocedures, such as managing permissions, creating procedures, invokingprocedures, and altering and dropping stored procedures.Related concepts:“SQL commands for stored procedures” on page 1-2

Manage user account permissionsBefore you create any stored procedures, familiarize yourself with the requiredaccount permissions necessary to create and manage these objects. The IBMNetezza admin user has full permission to manage and execute stored procedures.The database owner also has full permission to objects within the database that theowner owns. For release 7.0.3 and later systems that support multiple schemas in adatabase, the schema owner also has full permission to objects within that schema.In addition, the owner of the stored procedure has permission to manage andexecute the stored procedure.

As the admin user or any user who has account management permissions, you cangrant other users permission to create, manage, or execute the stored procedureson a Netezza system. You can assign permissions by using the IBM NetezzaPerformance Portal User's Guide, NzAdmin user interface, or by using the GRANTand REVOKE SQL commands. For details about managing users and groups, andassigning permissions by using the NzAdmin interface, see the IBM Netezza SystemAdministrator’s Guide.

If you use SQL commands to manage account permissions, the database to whichyou are connected has meaning when you run the GRANT command. If you areconnected to the SYSTEM database, the privilege applies to all databases. If youare connected to a specific database, the privilege applies only within thatdatabase.

Starting in release 7.0.3, you can use a fully qualified object notation to set thescope of object privileges from any database. The fully qualified object notation hasthe format database.schema.object, where:v database is a specific database name or the keyword ALL to grant the privilege

across all databases.v schema is a specific schema name or the keyword ALL for all schemas in the

specified database value.v object is the class PROCEDURE for all stored procedures, or a full signature

such as customer(VARCHAR(20)).

Make sure that you specify the correct signature for the object, including the sizesfor numeric and string data types, otherwise you receive an error similar to thefollowing example:ERROR: GrantRevokeCommand: existing UDX NAME(ARGS) differs in size ofstring/numeric arguments

You can use a similar format to set the scope of administrative privileges from anydatabase. The scope notation has the format IN database.schema, where:

© Copyright IBM Corp. 2009, 2014 3-1

Page 54: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

v database is a specific database name or the keyword ALL to grant the privilegeacross all databases. You can omit a database name.

v schema is a specific schema name or the keyword ALL for all schemas in thespecified database. If you omit the database name, the scope is for ALL schemasor all the schemas of the specified name.

Grant Create Procedure administration permission

To grant Create Procedure administration permission, use the following command:GRANT CREATE PROCEDURE TO entity;

For example, the following command grants Create Procedure permissions to theuser bsmith:GRANT CREATE PROCEDURE TO bsmith;

If you run this command while connected to the SYSTEM database, the privilege isgranted to the user in all databases. If you are connected to a specific database, theprivilege is granted to the user in only that database.

Using the release 7.0.3 fully qualified name form, you could also issue thecommand from any database and specify an IN clause to set the privilege scope.For example, the following command grants the user Create Procedure privilege inall databases and schemas:GRANT CREATE PROCEDURE IN ALL.ALL TO bsmith;

The following command grants the user Create Procedure privilege in the databasenamed NORTH and the schema named SALES:GRANT CREATE PROCEDURE IN NORTH.SALES TO bsmith;

Grant all object permissions

To grant users or a group with all object permissions, use the following command:GRANT ALL ON PROCEDURE TO entity;

This command gives the user or group the Alter, Drop, List, and Execute privilegesfor procedures and other permissions such as Insert, Delete, and others that are notused for procedures.

For example, the following command grants object permissions to the user bsmith:GRANT ALL ON PROCEDURE TO bsmith;

For example, the following command grants object permissions to the user bsmith,and is scoped to the database (and schema, if applicable) in which you run thecommand:GRANT ALL ON PROCEDURE TO bsmith;

Revoke Create Procedure administration permission

To revoke Create Procedure administration permission, use the followingcommand:REVOKE CREATE PROCEDURE FROM entity;

For example, the following command revokes Create Procedure permissions fromthe group analysts:

3-2 IBM Netezza Stored Procedures Developer's Guide

Page 55: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

REVOKE CREATE PROCEDURE FROM GROUP analysts;

Manage the Alter permission

To grant Alter permission on an object, use the following command:GRANT ALTER ON object TO entity;

To revoke Alter permission on an object, use the following command:REVOKE ALTER ON object FROM entity;

For example, to grant Alter permissions for the sample stored procedurereturntwo() to the user asmith:GRANT ALTER ON returntwo(timestamp) TO asmith;

For example, to revoke Alter permissions on the returntwo() procedure from thegroup sales:REVOKE ALTER ON returntwo(timestamp) FROM GROUP sales;

Manage the Execute permission

To grant Execute permission on an object, use the following command:GRANT EXECUTE ON object TO entity;

To revoke Execute permission on an object, use the following command:REVOKE EXECUTE ON object TO entity;

For example, to grant Execute permissions for the sample procedure returntwo()to the user bsmith:GRANT EXECUTE ON returntwo(timestamp) TO bsmith;

For example, to revoke Execute permissions for the sample procedure returntwo()from the group sales:REVOKE EXECUTE ON returntwo(timestamp) FROM GROUP sales;

Manage the Drop permission

To grant Drop permission on an object, use the following command:GRANT DROP ON object TO entity;

To revoke Drop permission on an object, use the following command:REVOKE DROP ON object FROM entity;

For example, to grant Drop permissions for the sample procedure returntwo() tothe user pcollins:GRANT DROP ON returntwo(timestamp) TO pcollins;

For example, to revoke Drop permissions for the sample procedure returntwo()from the user bsmith:REVOKE DROP ON returntwo(timestamp) FROM bsmith;

Related tasks:“How to create and use a stored procedure” on page 1-3

Chapter 3. Create and manage stored procedures 3-3

Page 56: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Create a stored procedureThe process to create a stored procedure is straightforward; typically, thetime-consuming work is in the design of the stored procedure, and the debuggingand testing of the procedure.

This section describes the following key steps for creating a stored procedure:v Design a stored procedurev Create a stored procedure

Design a stored procedureThe first step is to design the procedure itself. Make sure that you outline the basicpurpose and actions of the procedure, consider helpful error logging, and plan forexception handling. Review the NZPLSQL language and statements to create thebody of the procedure.

Create a stored procedureAfter you create the body of the stored procedure, you add it by using theCREATE [OR REPLACE] PROCEDURE command. You enter this command at aSQL command prompt.

The CREATE PROCEDURE command creates a procedure. To use this command,you must be the admin user, own the database, own the schema (multi-schemasystems), or have the Create Procedure privilege. The CREATE OR REPLACEPROCEDURE command creates a procedure if one does not already exist with thespecified signature, or updates an existing procedure with the matching signaturefor the new (or different) field values. To replace a procedure, you must have theAlter privilege.

For example, the following procedure customer() writes a customer name string tothe database log by using the RAISE NOTICE statement:TEST.TESTSCH(USR)=> CREATE PROCEDURE customer()RETURNS INT4 LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINRAISE NOTICE ’The customer name is alpha’;

END;END_PROC;CREATE PROCEDURE

Since the execution user permissions were not specified on the command line, thecommand uses the default of EXECUTE AS OWNER.

If you want to change the customer procedure to specify a new return value, youcan use a CREATE OR REPLACE PROCEDURE command similar to the following,but you must specify all the required fields (such as language and the completeprocedure body) even if their values did not change, as follows:TEST.TESTSCH(USR)=> CREATE OR REPLACE PROCEDURE customer()RETURNS INT8 LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINRAISE NOTICE ’The customer name is alpha’;

END;END_PROC;CREATE PROCEDURE

3-4 IBM Netezza Stored Procedures Developer's Guide

Page 57: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

You can also use the ALTER PROCEDURE command to modify certaincharacteristics of a defined procedure.Related concepts:“Alter a stored procedure” on page 3-10

Procedure signaturesEach stored procedure has a signature; that is, a unique identification in the form<procedure_name>(<argument_type_list>). Signatures must be unique within thesame database; that is, they cannot duplicate the signature of another storedprocedure. The <argument_type_list> component does not consider data type sizesto be differentiators. For example, you cannot create two procedures calledmyproc(numeric(3,2)) and myproc(numeric(4,1)) in the same database. The largernumeric size is not sufficient to create a unique signature.

If there are common use-cases where a procedure must accept different-sizedstrings or numerics, you can design the procedure to accept the largest of thepossible values, or you can create a stored procedure with a different name toprocess the different data size, for example:TEST.TESTSCH(USR)=> CREATE PROCEDURE myproc_lgnum(numeric(4,1))...

Procedures for overloadingYou can create stored procedures that have the same procedure name, but whichhave different argument signatures and return types. This process is calledoverloading the procedure definition.

For example, assume that you have a procedure called customer_name() that cantake two or three input strings, which represent the first, middle (if specified), andsurname of a customer.

The following example is some sample procedure definitions:TEST.TESTSCH(USR)=> CREATE PROCEDURE customer_name(VARCHAR(30), VARCHAR(30))...TEST.TESTSCH(USR)=> CREATE PROCEDURE customer_name(VARCHAR(30), VARCHAR(30),VARCHAR(30))...

If a user calls customer_name with two input strings, the system uses the first (twoargument) procedure. If the user specifies three input strings, the procedure usesthe second procedure that accepts three input strings.

You can use overloading to support different combinations of input values andreturn types. However, overloading and uniquely named but similar procedureshave a maintenance overhead; if you need to update or redesign the body of theprocedure, update each procedure definition with the changes that you want tomake.

Size-specific, generic, and variable argument proceduresIn the signature of a stored procedure, the <argument_type_list> can use threegeneral forms: size-specific arguments, generic arguments, and variable arguments.This section describes these three formats and the benefits and considerations forusing that type.

Size-specific argumentsWith size-specific arguments, you declare the type and size of all input arguments,and the type and size of the return value. Specific data type size declarations are

Chapter 3. Create and manage stored procedures 3-5

Page 58: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

useful for error-checking of the input arguments and return values, but they can besomewhat limiting if your procedure processes strings or numerics that can vary insize when you run a query.

For example, the following example creates a stored procedure that takes a stringof up to 20 VARCHAR characters:TEST.TESTSCH(USR)=> CREATE PROCEDURE customer(VARCHAR(20))RETURNS INT4 LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINremaining text omitted for example...

Constant data type sizes can result in implicit casts, such as casting a smaller inputvalue to fit a larger declared size. For example, it can increase the precision of anumeric or add padding to strings. If you choose too small a size, you risk loss ofprecision if IBM Netezza casts a larger input numeric to a smaller numeric ortruncates input strings that exceed the input argument size.

Generic-size argumentsGeneric-size (or any-size) arguments offer more flexibility for strings and numerics.You can declare character strings or numerics by using the ANY keyword in thesignature (or in the return value). For example:TEST.TESTSCH(USR)=> CREATE PROCEDURE customer(VARCHAR(ANY))RETURNS VARCHAR(ANY) LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINremaining text omitted for example...

The stored procedure accepts an input string of up to 64,000 characters (themaximum for a VARCHAR). Within the body of the stored procedure, the codemust process the strings and numerics with the plan that you can receive a stringof any valid length. That is, you can check and obtain their size, process them asneeded, and return the value for the procedure.

Generic-size arguments help you to avoid specific limits for the input strings andnumerics, or to use overly large or maximum size values that result in unnecessaryresource allocation for the procedure. This format can also reduce the need toregister and maintain similar procedures that take different input arguments orhave different return values, and possible casting of input values.

Supported generic argument types: You use the ANY keyword to indicate that anargument is generic. The following data types support the ANY keyword as a sizespecifier:v CHAR or NCHARv VARCHAR or NVARCHARv NUMERIC

For example, to specify a numeric data type of precision 10 and scale 2, youspecify it as NUMERIC(10,2). To specify a numeric data type that can take anysize, you specify is as NUMERIC(ANY). Likewise, to specify a variable characterstring that can take any size, you declare it as VARCHAR(ANY).

Generic arguments in the procedure signature: You can define generic argumentsand the standard data-type-and-size-specific arguments in the signature of a storedprocedure. The IBM Netezza software verifies that all the input arguments matchthe required number and data types of the signature.

3-6 IBM Netezza Stored Procedures Developer's Guide

Page 59: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

For arguments that have a specific size, the Netezza software also confirms that thesize of the input value matches the defined signature size. If necessary, the Netezzasoftware casts the input values to match the size specified in the signature. Forexample, if you declare a string of 20 characters [CHAR(20)] in a signature, theNetezza software implicitly truncates an input string that is longer than 20characters or adds padding if the input string is less than 20 characters.

For generic arguments, the argument values are passed to the procedure withoutany casting or changes. For example, if you declare a CHAR(ANY) input value, theprocedure accepts character strings of any length up to the supported maximum; itchecks to make sure that the input value is a valid character string and that itoccurs in the expected place of the signature.

The Netezza software performs some implicit castings for the input values. Forexample, if you define an input argument as VARCHAR(ANY) in the signature,but you pass an input of CHAR(200) to the procedure, the procedure casts theCHAR(200) to VARCHAR(200). The procedure uses the data type of the signatureand the size of the input value to determine the casting change.

Generic procedure return value:

If you use ANY for a return value size, your procedure calculates the size of thenumeric or string return value from the RETURN expression and returns it.

Register generic procedures: When you register a stored procedure that usesgeneric arguments, you use the keyword ANY to declare character or numeric datatypes as generic.

An example follows:MYDB.TESTSCH(USR)=> CREATE PROCEDURE itemfind(NUMERIC(ANY))RETURNS CHAR(ANY) LANGUAGE NZPLSQL ASBEGIN_PROC

BEGIN/* Body of procedure... intentionally omitted from example*/

END;END_PROC;

In this example, the itemfind() procedure takes an input numeric data type of anyvalid size and returns char value of any size.Related reference:“The CREATE [OR REPLACE] PROCEDURE commands” on page A-5

Variable argumentsVariable-argument procedures offer even more flexibility than generic-sizearguments. With variable argument procedures, you specify only the VARARGSkeyword in the argument_type_list. Users can specify from 0 to 64 input values ofany supported data type as input arguments. For example:TEST.TESTSCH(USR)=> CREATE PROCEDURE customer(VARARGS)RETURNS VARCHAR(ANY) LANGUAGE NZPLSQL ASBEGIN_PROC

BEGINremaining text omitted for example...

Within the body of the stored procedure, the code must process the input valuesand manage them as needed.

Chapter 3. Create and manage stored procedures 3-7

Page 60: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Use variable argument procedures to create one procedure that can be used fordifferent combinations of input types. This process simplifies the development ofstored procedures and reduces the need to create overloaded procedure definitionsthat do the same task for different types and numbers of arguments.Related concepts:“Argument list and variables” on page 2-6

Obfuscate the procedure bodyAs shown in CREATE PROCEDURE examples, the procedure body is entered inreadable text format. Users who have permission to show the procedure can usethe VERBOSE option to review the procedure body. If your procedure bodycontains intellectual property, copyrighted material, or other algorithms that youdo not want in clear text, you can obfuscate the body text.Related concepts:“Block quoting support” on page 1-5“Show information about a stored procedure” on page 3-12

Create obfuscated procedures by using a wrapping procedureA common way to create an obfuscated stored procedure is by creating a storedprocedure “wrapper” that takes the procedure definition and the procedure body,and creates the obfuscated procedure, as in the following example:TEST.TESTSCH(USR)=> CREATE OR REPLACE PROCEDURE wrap_proc(text, text)RETURNS BOOL LANGUAGE NZPLSQL ASBEGIN_PROC

DECLAREproc alias for $1;body alias for $2;enc text;sql text;BEGIN

enc := wrap_nzplsql(body);sql := proc || ’’ || ’’ || quote_literal(enc) || ’’;RAISE NOTICE ’%;’, sql;EXECUTE IMMEDIATE sql;return true;

END;END_PROC;CREATE PROCEDURE

Call the wrap_proc() procedure and specify the CREATE OR REPLACE maindefinition in the first input value; then specify the BEGIN PROC/END PROCcontents in the second input value. You must surround the main definition (thefirst input value) with single quotation marks. Do not enclose the second inputvalue (the procedure body) in single quotation marks because the wrap_nzplsql()built-in procedure takes the text as it would be specified for a CREATE ORREPLACE PROCEDURE command. An example follows:TEST.TESTSCH(USR)=> CALL wrap_proc(’CREATE OR REPLACE PROCEDURE customer()RETURNS INT4 LANGUAGE NZPLSQL AS’,BEGIN_PROC

BEGINRAISE NOTICE ’The customer name is alpha’;

END;END_PROC);NOTICE: CREATE OR REPLACE PROCEDURE customer() RETURNS INT4 LANGUAGENZPLSQLAS’TlpQU1FMV1JBUDEwWWk5NUhrQzVhR0xyRFRxTWR3VE5sQT09JEdFQ1B5LzVkSU1KMTI1a0dUK3NTWjlkb3ZGL3ZHalhpVExPVG5UajRkK3gxSkxvZVhKejdZQmJOVHN0aU1waFRlbmhoaWtYdHJUTVkKUUNrWDY5Nko5Rms2NlBIYUxra21xeWNZYXdWclBCQT0=’;

3-8 IBM Netezza Stored Procedures Developer's Guide

Page 61: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

wrap_proc-----------t(1 row)

When you call an obfuscated procedure, the system uses internal routines to“read” the obfuscated body text and run the procedure. The behavior and outputof the obfuscated procedure is identical to a cleartext version of the procedure, forexample:TEST.TESTSCH(USR)=> CALL customer();NOTICE: The customer name is alphacustomer----------(1 row)

Create obfuscated procedure body textAs an alternative to using the wrap_proc() procedure method, you can also createthe obfuscated body of the procedure in a separate step as follows:TEST.TESTSCH(USR)=> CALL wrap_nzplsql(BEGIN_PROC BEGIN RAISE NOTICE ’Thecustomer name is alpha’; END; END_PROC);

wrap_nzplsql----------------------------------------------------------------------TlpQU1FMV1JBUDEwVE5jZlh5TnpYbndCNkV5VFFMRTBiQT09JGE5N2p6ZEdJSVZwTTRrWmRRM0I3WmUxZERZeWd6YkdjTWkxTzQrL1dCMmpqRGQvak9lUzFQQjArNGdlM08yZVdxUjRIMTFaTnROUmwKdk5xSm0wb1RPZz09(1 row)

The wrap_nzplsql() built-in procedure generates the obfuscated body text, whichyou can input directly to a CREATE OR REPLACE PROCEDURE command, asfollows:TEST.TESTSCH(USR)=> CREATE OR REPLACE PROCEDURE customer() RETURNS INT4LANGUAGE NZPLSQL AS’TlpQU1FMV1JBUDEwVE5jZlh5TnpYbndCNkV5VFFMRTBiQT09JGE5N2p6ZEdJSVZwTTRrWmRRM0I3WmUxZERZeWd6YkdjTWkxTzQrL1dCMmpqRGQvak9lUzFQQjArNGdlM08yZVdxUjRIMTFaTnROUmwKdk5xSm0wb1RPZz09’;CREATE PROCEDURE

As shown in the example, you must enclose the obfuscated body text in singlequotation marks for the CREATE OR REPLACE PROCEDURE command.

Create obfuscated procedure definitions for a registration scriptIf you plan to create a script that users run to register your stored procedures intheir databases, you can use a wrapping procedure that takes as input theprocedure definition and body, and which returns a CREATE OR REPLACEPROCEDURE command that has obfuscated body text. For example:TEST.TESTSCH(USR)=> CREATE OR REPLACE PROCEDURE return_wrap(TEXT, TEXT)RETURNS TEXT LANGUAGE NZPLSQL ASBEGIN_PROC

DECLAREproc alias for $1;body alias for $2;enc text;sql text;BEGIN

enc := wrap_nzplsql(body);sql := proc || ’ ’ || ’’ || quote_literal(enc) || ’’;return sql;

END;END_PROC;CREATE PROCEDURE

Chapter 3. Create and manage stored procedures 3-9

Page 62: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Similar to the wrap_proc() procedure, specify the CREATE OR REPLACE maindefinition as a quoted text string in the first input value, and specify the unquotedBEGIN PROC/END PROC contents in the second input value. For example:TEST.TESTSCH(USR)=> CALL return_wrap(’CREATE OR REPLACE PROCEDURE customer()RETURNS INT4 LANGUAGE NZPLSQL AS’, BEGIN_PROC BEGIN RAISE NOTICE ’Thecustomer name is alpha’; END; END_PROC);

return_wrap----------------------------------------------------------------------CREATE OR REPLACE PROCEDURE customer() RETURNS INT4 LANGUAGE NZPLSQLAS’TlpQU1FMV1JBUDEwaTVJeHJnV1BLd1o0ZDVtNEtNMGxKQT09JCtiSlVDS1NHbkVrdVZja01JR3Nrc2dTZlExWDdkaUpDeHdZWUp2dmlrUkZIeEpEQnR6dE1JSHMxOHRTR08xMG1IczJFSk92R2F0Ti8KMGhKTGlUUEdIZz09’(1 row)

The return value is a CREATE OR REPLACE PROCEDURE command that you canuse in your registration script to define your stored procedure without displayingthe procedure body text to the script user.

Call or invoke a stored procedureTo invoke or execute the sample stored procedure customer(), you can use any ofthe following SQL query forms:TEST.TESTSCH(USR)=> CALL customer();TEST.TESTSCH(USR)=> EXEC customer();TEST.TESTSCH(USR)=> EXECUTE customer();TEST.TESTSCH(USR)=> EXECUTE PROCEDURE customer();TEST.TESTSCH(USR)=> SELECT customer();

Any of these commands cause the procedure to output the following:NOTICE: The customer name is alphaCUSTOMER----------

(1 row)

Related reference:Appendix A, “SQL command reference,” on page A-1

Alter a stored procedureAfter you define a stored procedure on the IBM Netezza system, you can use theALTER PROCEDURE command to change some aspects of the procedure.

You can modify a stored procedure to change the following aspects of theprocedure:v RETURNS valuev Execution user property (EXECUTE AS OWNER versus EXECUTE AS CALLER)v The body of the procedurev The owner of the procedure

You cannot change the procedure name or argument type list. You must drop theexisting procedure and create a procedure with the new name and argument typelist.

For example, the following sample commands can be used to change the“customer” procedure. To change the return value type, use a command similar tothe following example:

3-10 IBM Netezza Stored Procedures Developer's Guide

Page 63: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

TEST.TESTSCH(USR)=> ALTER PROCEDURE customer() RETURNS INT8;ALTER PROCEDURE

To change the owner of the procedure to user, use a command similar to thefollowing example:TEST.TESTSCH(USR)=> ALTER PROCEDURE customer() OWNER TO user ;ALTER PROCEDURE

To change the user execution property to EXECUTE AS CALLER, use a commandsimilar to the following example:TEST.TESTSCH(USR)=> ALTER PROCEDURE customer() EXECUTE AS CALLER;ALTER PROCEDURE

To change the procedure definition, use a command similar to the followingexample:TEST.TESTSCH(USR)=> ALTER PROCEDURE customer() ASBEGIN_PROC

BEGINRAISE NOTICE ’The customer name is beta’;

END;END_PROC;ALTER PROCEDURE

Related concepts:“Create a stored procedure” on page 3-4Related reference:“The ALTER PROCEDURE command” on page A-1

Comment on a stored procedureAs a best practice, add some descriptive comments on stored procedures by usingthe COMMENT ON command capability.

For example:COMMENT ON PROCEDURE customer() IS ’A procedure that displays acustomer name.’;COMMENT

An IBM Netezza SQL query user can display these comments by using the nzsql\dd <name> command switch, or the \dd switch shows all comments for allprocedures. Consider using a comment template that includes information aboutthe author, version, and description in the following format:COMMENT ON PROCEDURE <procedure name> (<argument type list>) IS’Author: <name>Version: <version>Description: <description>’;

For example:COMMENT ON PROCEDURE customer() IS ’Author: bsmithVersion: 1.0 Description: A procedure that writes a customer name tothe database log file.’;

To comment on a stored procedure, you must either be the Netezza admin user,the owner of the procedure, or you must have Alter permissions for procedureobjects. For more information about COMMENT ON, see the IBM Netezza DatabaseUser’s Guide.

Chapter 3. Create and manage stored procedures 3-11

Page 64: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Make sure that you specify a full procedure name and argument list, includingcorrect sizes for numeric and string data types. Otherwise, you receive an errorsimilar to the following example:Error: CommentProcedure: existing procedure name(argument type list)differs in size of string/numeric arguments

Drop a stored procedureYou can remove a stored procedure from the IBM Netezza system by using theDROP PROCEDURE command.

For example, to drop the customer procedure, use a command similar to thefollowing example:DROP PROCEDURE customer();DROP PROCEDURE

Related reference:“The DROP PROCEDURE command” on page A-7

Show information about a stored procedureYou can use the SHOW PROCEDURE command to display information about astored procedure.

A sample command follows for the example customer procedure:MYDB.TESTSCH(USR)=> SHOW PROCEDURE customer;RESULT | PROCEDURE | BUILTIN | ARGUMENTS---------+-----------+---------+-----------INTEGER | CUSTOMER | f | ()(1 row)

The sample output shows the return value (RESULT), the procedure name, f (false)to indicate that this is a user-defined procedure (not a built-in or system-suppliedprocedure), and the argument list for the procedure (an empty list in this example).

The command displays information for any procedures with names that begin withthe specified characters. For example, if you have two procedures named customerand customerid, this example command displays information for both procedures.

The command also offers a VERBOSE mode that displays more information aboutthe procedure, including the procedure body, comments (if supplied), owner,execution user, and other information. If the procedure is obfuscated, theprocedure body is not in clear text; it is in an unreadable format.Related concepts:“Obfuscate the procedure body” on page 3-8Related reference:“The SHOW PROCEDURE command” on page A-9

NzAdmin administrative interface for stored procedures

If you use the NzAdmin administrative interface, you can view information aboutthe stored procedures defined on a IBM Netezza system and manage them. Youcannot add or alter a stored procedure from the NzAdmin interface, but you candisplay its properties, change its owner, drop the procedure, and manage user andgroup permissions for procedures.

3-12 IBM Netezza Stored Procedures Developer's Guide

Page 65: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

To view the stored procedures, go to the Database tab of NzAdmin. Select adatabase and double-click Procedures to list the stored procedures that are definedin that database.

The Procedures list shows the signature, return type, owner, and creation date ofeach procedure. Double-click a procedure to obtain information about theprocedure definition, or to view or manage the privileges for the procedure. Formore information about using the NzAdmin interface, see the IBM Netezza SystemAdministrator’s Guide.

Figure 3-1. The NzAdmin stored procedures window

Chapter 3. Create and manage stored procedures 3-13

Page 66: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

3-14 IBM Netezza Stored Procedures Developer's Guide

Page 67: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Appendix A. SQL command reference

This section describes the IBM Netezza SQL commands that relate to the creationand management of stored procedures.

The following table lists the SQL commands.

Table A-1. Stored procedure SQL commands

Command Description More information

ALTER PROCEDURE Changes a storedprocedure.

“The ALTER PROCEDURE command.”

CALL or EXEC[UTE [PROCEDURE]]

Runs a storedprocedure.

“The CALL and EXEC[UTE[PROCEDURE]] commands” on pageA-3

CREATE [OR REPLACE]PROCEDURE

Adds or updates astored procedure.

“The CREATE [OR REPLACE]PROCEDURE commands” on pageA-5.

DROP PROCEDURE Drops or deletes astored procedure.

“The DROP PROCEDURE command”on page A-7.

SHOW PROCEDURE Displaysinformation aboutstored procedures.

“The SHOW PROCEDURE command”on page A-9.

Related concepts:“Call or invoke a stored procedure” on page 3-10“How to execute a stored procedure” on page 1-3“SQL commands for stored procedures” on page 1-2

The ALTER PROCEDURE commandUse the ALTER PROCEDURE command to change a stored procedure.

You can change the return value, execution setting, owner, and body of aprocedure, but you cannot change the name or argument list with this command.You can add or remove the VARARGS value in an otherwise empty argument list.

To change the name or argument list of a stored procedure, you must drop theprocedure and create a procedure with the new name or argument type list.

SynopsisALTER PROCEDURE <name> (<args>) [ RETURNS <type>][ EXECUTE AS OWNER | EXECUTE AS CALLER ] [AS <procedure_body>];ALTER PROCEDURE <name> (<args>) OWNER TO <user>;

© Copyright IBM Corp. 2009, 2014 A-1

Page 68: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Inputs

The ALTER PROCEDURE command takes the following inputs:

Table A-2. ALTER PROCEDURE input

Input Description

name The name of the stored procedure that you want to change. You cannotchange the name of the procedure. The procedure must be defined inthe database to which you are connected.

For systems that support multiple schemas, you can specify a name inthe format schema.procedure to change a procedure in a differentschema of the current database.

args A list of input argument data types for the stored procedure. You canalso specify the VARARGS value to create a variable argumentprocedure where users can input up to 64 values of any supported datatype. VARARGS is a mutually exclusive value; you cannot specify anyother arguments in the list.

You cannot change the argument list or sizes. You can removeVARARGS from the argument list, or add it to an otherwise emptyargument list.

RETURNS <type> Specifies the type of data returned by the procedure. The <type> valuecan be a IBM Netezza data type or the value REFTABLE (<table-name>)to indicate that it returns a result set that looks like the specified table.The table must exist, and it continues to exist after the procedure. Thetable can be empty, but it must exist in the database.

EXECUTE ASOWNER

If specified, the stored procedure uses the procedure owner ID for allaccess control and permission checks. This is the default.

EXECUTE ASCALLER

If specified, the stored procedure uses the ID of the user who called theprocedure for all access control and permission checks.

procedure_body Specifies the text or body of the procedure. The body must be enclosedwith single quotation marks or enclosed by a BEGIN_PROC/END_PROC pair.

When you alter the procedure, you can obfuscate the body to mask thecontent from users who have permission to show the procedure.

Outputs

The ALTER PROCEDURE command has the following output

Table A-3. ALTER PROCEDURE Output

Output Description

ALTER PROCEDURE The message that the system returns if the commandis successful.

ERROR: replacing procedure:permission denied.

The message indicates that the user does not haveAlter permission on the procedure.

Error: FunctionAlter: existing UDXNAME(ARGS) differs in size ofstring/numeric arguments

This error indicates that a stored procedure existswith the name but has different sizes specified forstring or numeric arguments.

To alter the stored procedure, make sure that youspecify the exact argument type list with correct sizes.

A-2 IBM Netezza Stored Procedures Developer's Guide

Page 69: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Table A-3. ALTER PROCEDURE Output (continued)

Output Description

ERROR: FunctionAlter: functionNAME does not exist with thatsignature

This error indicates that the specified procedure namedoes not exist in the database.

ERROR: Can't specify arguments toa varargs procedure

You cannot specify both the VARARGS value and anyother argument value in the arguments list. TheVARARGS value is mutually exclusive.

Description

You cannot alter a stored procedure that is currently in use in an active query.After the transaction completes for an active query, the Netezza system processesthe ALTER PROCEDURE command.

Privileges requiredTo alter a procedure, you must meet one of the following criteria:v You must have the Alter privilege on the PROCEDURE object.v You must have the Alter privilege on the specific procedure.v You must own the procedure.v You must be the database admin user or own the current database or the

current schema on systems that supports multiple schemas.

Common tasksYou can use the ALTER PROCEDURE command to change the executionuser ID of the procedure, its return value, or the procedure body itself.

You can also use the ALTER PROCEDURE command to change the ownerof a procedure as follows:ALTER PROCEDURE <name> (<arguments>) OWNER TO <name>;

Usage

To change the execution ID from over to caller, enter:system(admin)=> ALTER PROCEDURE myproc(int4) EXECUTE AS CALLER;

To change the owner for a procedure in a different schema, enter:MYDB.MYSCH(USER)=> ALTER PROCEDURE schtwo.myproc(int4) OWNER TOuser2;

Related concepts:“Alter a stored procedure” on page 3-10

The CALL and EXEC[UTE [PROCEDURE]] commandsUse the CALL command, EXEC command, EXECUTE command, or EXECUTEPROCEDURE command to invoke a stored procedure on a IBM Netezza host.

The CALL, EXEC, EXECUTE, EXECUTE PROCEDURE commands are identical intheir behavior, inputs, and outputs. The different commands provide compatibilitywith other procedural language invocation methods. You can also use the SELECTcommand to invoke a stored procedure.

Appendix A. SQL command reference A-3

Page 70: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

SynopsisCALL procedure_name(arguments)EXEC procedure_name(arguments)EXECUTE procedure_name(arguments)EXECUTE PROCEDURE procedure_name(arguments)SELECT procedure_name(arguments)

Inputs

The CALL and EXEC[UTE [PROCEDURE] commands take the following inputs:

Table A-4. CALL and EXEC[UTE [PROCEDURE]] inputs

Input Description

procedure_name The name of the stored procedure that you want to invoke. If youspecify only a procedure name, the system searches the currentdatabase and schema, and then search PATH to find the procedure.

You can specify a fully qualified object name to execute a proceduredefined in a different database or schema.

arguments Specifies a list of constant or literal arguments to the procedure. Thearguments might be results of functions when the functions take onlyconstant or literal arguments as well.

Outputs

The CALL and EXEC[UTE [PROCEDURE] commands have the following outputs:

Table A-5. CALL and EXEC[UTE [PROCEDURE]] outputs

Output Description

ERROR:EXECUTE PROC:Permissiondenied.

This error indicates that the current user account does not have Executepermission for the stored procedure.

ERROR: Function'NAME(ARGS)'does not exist

Unable toidentify afunction thatsatisfies theargument types

You might needto add explicittypecasts

This message indicates that the user entered incorrect arguments for thestored procedure. A procedure of that name exists, but it is expectingdifferent input arguments.

Description

Privileges requiredTo invoke a stored procedure, you must meet one of the following criteria:v You must have the Execute privilege on the PROCEDURE object.v You must have the Execute privilege on the specific procedure.v You must own the procedure.

A-4 IBM Netezza Stored Procedures Developer's Guide

Page 71: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

v You must be the database admin user or own the current database or thecurrent schema on systems that support multiple schemas.

Usage

The following examples provide some sample usage:MYDB.MYSCH(USER)=> CALL updateacct();MYDB.MYSCH(USER)=> EXEC schema_two.myproc();MYDB.MYSCH(USER)=> EXECUTE sales.dev.inventorysearch(umbrellas);MYDB.MYSCH(USER)=> EXECUTE PROCEDURE updateacct();

You can also use the SELECT command to run a procedure; however, you cannotspecify a FROM clause. For example:MYDB.MYSCH(USER)=> SELECT updateacct();MYDB.MYSCH(USER)=> SELECT inventorysearch(umbrellas);

The CREATE [OR REPLACE] PROCEDURE commandsUse the CREATE OR REPLACE PROCEDURE command to create a storedprocedure or to update an existing procedure with a new return type, executionpermissions, or procedure body.

SynopsisCREATE [OR REPLACE] PROCEDURE <name> (<arguments>)RETURNS <type> [ [ EXECUTE AS OWNER | EXECUTE AS CALLER ] ] LANGUAGENZPLSQL AS <procedure_body>;

Inputs

The CREATE OR REPLACE PROCEDURE command takes the following inputs:

Table A-6. CREATE OR REPLACE PROCEDURE inputs

Input Description

name The name of the stored procedure that you want to create or replace.This name is the SQL identifier that is used to invoke the procedure ina SQL expression.

If the stored procedure exists, you cannot change the name with theCREATE OR REPLACE command.

For systems that support multiple schemas, you can specify a name inthe format schema.procedure to create a procedure in a differentschema of the current database. You cannot create a procedure in adifferent database.

arguments Specifies a list of fully specified argument data types. You can alsospecify the VARARGS value to create a variable argument procedurewhere users can input up to 64 values of any supported data type.VARARGS is a mutually exclusive value; you cannot specify any otherarguments in the list.

If the stored procedure exists, you cannot change the argument type listwith the CREATE OR REPLACE command. You can change someaspects of the argument types; for example, you can change the size ofa string or the precision and scale of a numeric value. You can alsoremove VARARGS from the argument list, or add it to an otherwiseempty argument list.

Appendix A. SQL command reference A-5

Page 72: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Table A-6. CREATE OR REPLACE PROCEDURE inputs (continued)

Input Description

RETURNS <type> Specifies the type of data returned by the procedure. The <type> valuecan be an IBM Netezza data type or the value REFTABLE(<table-name>) to indicate that it returns a result set that looks like thespecified table. The table must exist, although it can be empty, and itcontinues to exist after the procedure.

EXECUTE ASOWNER

If specified, the stored procedure runs by using the procedure owner IDfor all access control and permission checks. This is the default.

EXECUTE ASCALLER

If specified, the stored procedure runs by using the ID of the user whocalled the procedure for all access control and permission checks.

LANGUAGE Specifies the programming language used for the procedure. Thedefault and only supported value is NZPLSQL.

procedure_body Specifies the text of the procedure and must be enclosed with singlequotation marks or a BEGIN_PROC/END_PROC pair.

You can obfuscate the body to mask the content from users who havepermission to show the procedure.

Outputs

The CREATE [OR REPLACE] PROCEDURE command has the following outputs:

Table A-7. CREATE [OR REPLACE] PROCEDURE outputs

Output Description

CREATE PROCEDURE The message that the system returns if the commandis successful.

ERROR: creating procedure:permission denied.

The message indicates that the user does not haveCreate Procedure permission.

ERROR: User 'username' is notallowed to create/drop procedures.

The system returns this message if your user accountdoes not have permission to create a storedprocedure.

ERROR: Synonym 'name' alreadyexists

The system returns this message if a synonym existswith the name that you specified for the storedprocedure.

ERROR: ProcedureCreate:procedure NAME already existswith the same signature

This error is returned when you issue a CREATEPROCEDURE command and a stored procedure withthe same name and argument type list exists in thedatabase. Use CREATE OR REPLACE PROCEDUREinstead.

NOTICE: FunctionCreate: existingUDX NAME(ARGS) differs in sizeof string/numeric arguments

This message indicates that a stored procedure existswith the name but has different sizes specified forstring or numeric arguments. If you did not intend tochange the stored procedure signature, check thesignature and ensure that it is correct.

ERROR: Can't specify arguments toa varargs procedure

You cannot specify both the VARARGS value and anyother argument value in the arguments list. TheVARARGS value is mutually exclusive.

A-6 IBM Netezza Stored Procedures Developer's Guide

Page 73: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Description

When you create a stored procedure, the signature of the stored procedure (that is,its name and argument type list) must be unique within its database. No otherstored procedure can have the same name and argument type list in the samedatabase.

You cannot change the stored procedure name or the argument type list with theCREATE OR REPLACE command. You can change some aspects of the argumenttypes; for example, you can change the size of a string or the precision and scale ofa numeric value, and you can add or remove the VARARGS value in an otherwiseempty argument list. To change the name or argument type list of a storedprocedure, you must drop the stored procedure and then create a stored procedurewith the new name or argument type list.

You cannot replace a stored procedure that is currently in use in an active query.After the transaction completes for an active query, the Netezza system processesthe CREATE OR REPLACE PROCEDURE command.

Privileges requiredYou must have Create Procedure permission to use the CREATEPROCEDURE command. Also, if you use CREATE OR REPLACEPROCEDURE to change a stored procedure, you must have CreateProcedure and Alter permission to change it.

Common tasksUse the CREATE PROCEDURE command to create and become the ownerof a new stored procedure. You can use the ALTER PROCEDUREcommand to change the owner of a procedure.

Usage

To create a procedure called customername:MYDB.SCHEMA(USER)=> CREATE OR REPLACE PROCEDURE customer() RETURNS INT8

LANGUAGE NZPLSQL AS BEGIN_PROC BEGIN RAISE NOTICE ’The customername is alpha’; END; END_PROC;

To create a new procedure called customername in a different schema of the samedatabase:MYDB.SCHEMA(USER)=> CREATE OR REPLACE PROCEDURE sch_two.customer()RETURNS INT8 LANGUAGE NZPLSQL AS BEGIN_PROC BEGIN RAISE NOTICE ’Thecustomer name is alpha’; END; END_PROC;

Related concepts:“Register generic procedures” on page 3-7

The DROP PROCEDURE commandUse the DROP PROCEDURE command to remove an existing stored procedurefrom a database.

SynopsisDROP PROCEDURE <name> (<arguments>)

Appendix A. SQL command reference A-7

Page 74: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Inputs

The DROP PROCEDURE command takes the following inputs:

Table A-8. DROP PROCEDURE inputs

Input Description

name The name of the stored procedure that you want to drop. Theprocedure must be defined in the database to which you are connected.

For systems that support multiple schemas, you can specify a name inthe format schema.procedure to drop a procedure in a different schemaof the current database. You cannot drop a procedure in a differentdatabase.

arguments A list of input arguments to uniquely identify the stored procedure.

Outputs

The DROP PROCEDURE command has the following outputs:

Table A-9. DROP PROCEDURE Outputs

Output Description

DROP PROCEDURE The message that the system returns if the commandis successful.

ERROR: DROP PROCEDURE:permission denied

The user does not have Drop permission.

ERROR: RemoveFunction: function'NAME(ARGS)' does not exist

The message that indicates that the specifiedprocedure signature does not exist in the database.

ERROR: Name: No such storedprocedure

The message that the system returns if the specifiedstored procedure does not exist in the currentdatabase.

ERROR: RemoveFunction: existingUDX NAME(ARGS) differs in sizeof string/numeric arguments

This error indicates that a stored procedure existswith the name but has different sizes specified forstring or numeric arguments.

To drop the stored procedure, make sure that youspecify the exact argument type list with correct sizes.

Description

You cannot drop a stored procedure that is currently in use in an active query.After the transaction completes for an active query, the IBM Netezza systemprocesses the DROP PROCEDURE command. The stored procedure must bedefined in the current database.

The DROP PROCEDURE command has the following characteristics:

Privileges requiredTo drop a stored procedure, you must meet one of the following criteria:v You must have the Drop privilege on the PROCEDURE object.v You must have the Drop privilege on the specific stored procedure.v You must own the stored procedure.v You must be the database admin user or own the current database or the

current schema on systems that supports multiple schemas.

A-8 IBM Netezza Stored Procedures Developer's Guide

Page 75: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Common tasksUse the DROP PROCEDURE command to drop an existing storedprocedure from a database.

Usage

To drop a sample stored procedure named mycalc(), enter:system(admin)=> DROP PROCEDURE mycalc();

Related concepts:“Drop a stored procedure” on page 3-12

The SHOW PROCEDURE commandUse the SHOW PROCEDURE command to display information about one or morestored procedures. The command checks your user account privileges to ensurethat you are permitted to see information about the procedures.

SynopsisSHOW PROCEDURE [ALL | <name>] [VERBOSE]

Inputs

The SHOW PROCEDURE command takes the following inputs:

Table A-10. SHOW PROCEDURE inputs

Input Description

ALL Show information about all the stored procedures defined in thedatabase. This is the default.

name Show information about one or more stored procedures defined in thedatabase. You can specify a partial name. The command displaysinformation for all the procedures with names that begin with thespecified characters. You cannot specify a full signature.

VERBOSE Display detailed information about the stored procedure.

Outputs

The SHOW PROCEDURE command has the following output:

Table A-11. SHOW PROCEDURE output

Output Description

error found "(" (at char num) syntaxerror, unexpected '(', expecting $end

The message that the system returns if you specify afull signature, for example:

show procedure returntwo();

Description

The SHOW PROCEDURE command has the following characteristics:

Privileges requiredAny user can run the SHOW PROCEDURE command. To see informationabout procedures in the output, you must be the admin user, own one ormore procedures, own the current database or the schema on a system that

Appendix A. SQL command reference A-9

Page 76: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

supports multiple schemas, or have object privileges (such as Execute, List,Alter, or Drop) on one or more procedures or the Procedure object class.

Common tasksUse the SHOW PROCEDURE command to display one or all storedprocedures in a database.

Usage

To show the sample stored procedure named returntwo, use the followingcommand:

MYDB.SCHEMA(ADMIN)=> SHOW PROCEDURE returntwo;RESULT | PROCEDURE | BUILTIN | ARGUMENTS

--------------------------+-----------+---------+-------------REFTABLE(MYDB.USER.TBL) | RETURNTWO | f | (TIMESTAMP)(1 row)

To show verbose information for the sample stored procedure named returntwo,use the following command. The sample output is formatted to fit the page area.

MYDB.SCHEMA(ADMIN)=> SHOW PROCEDURE returntwo VERBOSE;RESULT | PROCEDURE | BUILTIN | ARGUMENTS | OWNER | EXECUTEDASOWNER |

VARARGS | DESCRIPTION | PROCEDURESOURCE-------------------------+-----------+---------+-------------+-------+-----------------+--------+--------------+-----------------REFTABLE(MYDB.USER.TBL) | RETURNTWO | f | (TIMESTAMP) | USER | t |f |This is a sample stored procedure |

DECLAREBEGIN

EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (1,1)’;EXECUTE IMMEDIATE ’INSERT INTO ’ || REFTABLENAME ||’ values (2,2)’;RETURN REFTABLE;

END;

(1 row)

If the stored procedure is obfuscated, the VERBOSE mode shows the obfuscatedbody text, as follows:

MYDB.SCHEMA(ADMIN)=> SHOW PROCEDURE customer VERBOSE;RESULT | PROCEDURE | BUILTIN | ARGUMENTS | OWNER | EXECUTEDASOWNER | VARARGS |

DESCRIPTION | PROCEDURESOURCE-------------------------+-----------+---------+-------------+-------+-----------------+--------+--------------+-----------------BIGINT | CUSTOMER | f | () | USR | t | f |

| TlpQU1FMV1JBUDEwVE5jZlh5TnpYbndCNkV5VFFMRTBiQT09JGE5N2p6ZEdJSVZwTTRrWmRRM0I3WmUxZERZeWd6YkdjTWkxTzQrL1dCMmpqRGQvak9lUzFQQjArNGdlM08yZVdxUjRIMTFaTnROUmwKdk5xSm0wb1RPZz09(1 row)

To list all the stored procedures in a database, enter:MYDB.SCHEMA(ADMIN)=> SHOW PROCEDURE ALL;

RESULT | PROCEDURE | BUILTIN | ARGUMENTS----------------------------+------------------+---------+------------------------BOOLEAN | BOOLPROC | f | (BOOLEAN)CHARACTER | CHARPROC | f | (CHARACTER(ANY))CHARACTER | CHARPROCANY | f | (CHARACTER(ANY))CHARACTER | CHARPROCANY2 | f | (CHARACTER(10))REAL | FLOAT4PROC | f | (REAL)DOUBLE PRECISION | FLOAT8PROC | f | (DOUBLE PRECISION)BYTEINT | INT1PROC | f | (BYTEINT)

Related concepts:“Show information about a stored procedure” on page 3-12

A-10 IBM Netezza Stored Procedures Developer's Guide

Page 77: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Appendix B. Stored procedure examples

This section contains examples of stored procedure definitions.

Variable argument stored procedureThe following is an example of a stored procedure that uses variable argumentsand the $var value to obtain the data type of the input parameters:CREATE OR REPLACE PROCEDURE sp_varargs01(varargs)

RETURNS INT4LANGUAGE NZPLSQLASBEGIN_PROC

DECLAREnum_args int4;typ oid;idx int4;

BEGINnum_args := PROC_ARGUMENT_TYPES.count;RAISE NOTICE ’Number of arguments is %’, num_args;for i IN 0 .. PROC_ARGUMENT_TYPES.count - 1 LOOP

typ := PROC_ARGUMENT_TYPES(i);idx := i+1;RAISE NOTICE ’argument $% is type % value ’’%’’’, idx, typ,

$idx;END LOOP;

END;END_PROC;

A sample call to the sp_varargs01 procedure follows:select sp_varargs01(true, ’test’::char(10), 62443234::int8, 123::int2,123456::int4, 34343.4343::float4, 1212.2323::float8,’test2’::varchar(10), ’2009-05-12’::date, ’13:14:05’::time,’2009-05-12 08:10:10’::timestamp, ’2 days 1 hour’::interval,’11:40:36+05’::timetz, 3243.4324234::numeric,3243.4324234::numeric(7,2), 5::int1, ’foo’::nchar(20),’foo’::nvarchar(20), null::int4);NOTICE: Number of arguments is 19NOTICE: argument $1 is type 16 value ’t’NOTICE: argument $2 is type 1042 value ’test ’NOTICE: argument $3 is type 20 value ’62443234’NOTICE: argument $4 is type 21 value ’123’NOTICE: argument $5 is type 23 value ’123456’NOTICE: argument $6 is type 700 value ’34343.4’NOTICE: argument $7 is type 701 value ’1212.2323’NOTICE: argument $8 is type 1043 value ’test2’NOTICE: argument $9 is type 1082 value ’2009-05-12’NOTICE: argument $10 is type 1083 value ’13:14:05’NOTICE: argument $11 is type 1184 value ’2009-05-12 08:10:10’NOTICE: argument $12 is type 1186 value ’2 days 01:00:00’NOTICE: argument $13 is type 1266 value ’11:40:36+05’NOTICE: argument $14 is type 1700 value ’3243.4324234’NOTICE: argument $15 is type 1700 value ’3243.43’NOTICE: argument $16 is type 2500 value ’5’NOTICE: argument $17 is type 2522 value ’foo ’NOTICE: argument $18 is type 2530 value ’foo’NOTICE: argument $19 is type 23 value ’<NULL>’sp_varargs01--------------

(1 row)

© Copyright IBM Corp. 2009, 2014 B-1

Page 78: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Example of simulating an anonymous blockThe following is an NZPLSQL procedure that can execute anonymous blocks:CREATE OR REPLACE PROCEDURE exec_nzplsql_block(text) RETURNS BOOLEANLANGUAGE NZPLSQL ASBEGIN_PROC

DECLARE lRet BOOLEAN;DECLARE sid INTEGER;DECLARE nm varchar;DECLARE cr varchar;

BEGINsid := current_sid;nm := ’any_block’ || sid || ’()’;cr = ’CREATE OR REPLACE PROCEDURE ’ || nm ||

’ RETURNS BOOL LANGUAGE NZPLSQL AS BEGIN_PROC ’|| $1 || ’ END_PROC’;

EXECUTE IMMEDIATE cr;EXECUTE IMMEDIATE ’SELECT ’ || nm;EXECUTE IMMEDIATE ’DROP PROCEDURE ’ || nm;RETURN TRUE;

END;END_PROC;

An example call and output follows:MYDB.SCHEMA(USER)=> call exec_nzplsql_block(BEGIN_PROC DECLARE var char;BEGIN var:= ’test’; raise NOTICE ’This is a %’, var; END; END_PROC);

NOTICE: This is a testEXEC_NZPLSQL_BLOCK--------------------t(1 row)

B-2 IBM Netezza Stored Procedures Developer's Guide

Page 79: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Notices

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document inother countries. Consult your local IBM representative for information on theproducts and services currently available in your area. Any reference to an IBMproduct, program, or service is not intended to state or imply that only that IBMproduct, program, or service may be used. Any functionally equivalent product,program, or service that does not infringe any IBM intellectual property right maybe used instead. However, it is the user's responsibility to evaluate and verify theoperation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matterdescribed in this document. The furnishing of this document does not grant youany license to these patents. You can send license inquiries, in writing, to: Thisinformation was developed for products and services offered in the U.S.A.

IBM Director of LicensingIBM CorporationNorth Castle DriveArmonk, NY 10504-1785 U.S.A.

For license inquiries regarding double-byte (DBCS) information, contact the IBMIntellectual Property Department in your country or send inquiries, in writing, to:

IBM World Trade Asia CorporationLicensing 2-31 Roppongi 3-chome, Minato-kuTokyo 106-0032, Japan

The following paragraph does not apply to the United Kingdom or any othercountry where such provisions are inconsistent with local law:INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THISPUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESSFOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express orimplied warranties in certain transactions, therefore, this statement may not applyto you.

This information could include technical inaccuracies or typographical errors.Changes are periodically made to the information herein; these changes will beincorporated in new editions of the publication. IBM may make improvementsand/or changes in the product(s) and/or the program(s) described in thispublication at any time without notice.

Any references in this information to non-IBM Web sites are provided forconvenience only and do not in any manner serve as an endorsement of those Websites. The materials at those Web sites are not part of the materials for this IBMproduct and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way itbelieves appropriate without incurring any obligation to you.

© Copyright IBM Corp. 2009, 2014 C-1

Page 80: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Licensees of this program who wish to have information about it for the purposeof enabling: (i) the exchange of information between independently createdprograms and other programs (including this one) and (ii) the mutual use of theinformation which has been exchanged, should contact:

IBM CorporationSoftware Interoperability Coordinator, Department 49XA3605 Highway 52 NRochester, MN 55901U.S.A.

Such information may be available, subject to appropriate terms and conditions,including in some cases, payment of a fee.

The licensed program described in this document and all licensed materialavailable for it are provided by IBM under terms of the IBM Customer Agreement,IBM International Program License Agreement or any equivalent agreementbetween us.

Any performance data contained herein was determined in a controlledenvironment. Therefore, the results obtained in other operating environments mayvary significantly. Some measurements may have been made on development-levelsystems and there is no guarantee that these measurements will be the same ongenerally available systems. Furthermore, some measurements may have beenestimated through extrapolation. Actual results may vary. Users of this documentshould verify the applicable data for their specific environment.

Information concerning non-IBM products was obtained from the suppliers ofthose products, their published announcements or other publicly available sources.IBM has not tested those products and cannot confirm the accuracy ofperformance, compatibility or any other claims related to non-IBM products.Questions on the capabilities of non-IBM products should be addressed to thesuppliers of those products.

All statements regarding IBM's future direction or intent are subject to change orwithdrawal without notice, and represent goals and objectives only.

All IBM prices shown are IBM's suggested retail prices, are current and are subjectto change without notice. Dealer prices may vary.

This information contains examples of data and reports used in daily businessoperations. To illustrate them as completely as possible, the examples include thenames of individuals, companies, brands, and products. All of these names arefictitious and any similarity to the names and addresses used by an actual businessenterprise is entirely coincidental.

COPYRIGHT LICENSE:

This information contains sample application programs in source language, whichillustrate programming techniques on various operating platforms. You may copy,modify, and distribute these sample programs in any form without payment toIBM, for the purposes of developing, using, marketing or distributing applicationprograms conforming to the application programming interface for the operatingplatform for which the sample programs are written. These examples have notbeen thoroughly tested under all conditions. IBM, therefore, cannot guarantee orimply reliability, serviceability, or function of these programs.

C-2 IBM Netezza Stored Procedures Developer's Guide

Page 81: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Each copy or any portion of these sample programs or any derivative work, mustinclude a copyright notice as follows:

© your company name) (year). Portions of this code are derived from IBM Corp.Sample Programs.

© Copyright IBM Corp. _enter the year or years_.

If you are viewing this information softcopy, the photographs and colorillustrations may not appear.

TrademarksIBM, the IBM logo, ibm.com® and Netezza are trademarks or registered trademarksof International Business Machines Corporation in the United States, othercountries, or both. If these and other IBM trademarked terms are marked on theirfirst occurrence in this information with a trademark symbol (® or ™), thesesymbols indicate U.S. registered or common law trademarks owned by IBM at thetime this information was published. Such trademarks may also be registered orcommon law trademarks in other countries. A current list of IBM trademarks isavailable on the web at "Copyright and trademark information" athttp://www.ibm.com/legal/copytrade.shtml.

Adobe is a registered trademark of Adobe Systems Incorporated in the UnitedStates, and/ or other countries.

Linux is a registered trademark of Linus Torvalds in the United States, othercountries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks ofMicrosoft Corporation in the United States, other countries, or both.

NEC is a registered trademark of NEC Corporation.

UNIX is a registered trademark of The Open Group in the United States and othercountries.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Othernames may be trademarks of their respective owners.

Red Hat is a trademark or registered trademark of Red Hat, Inc. in the UnitedStates and/or other countries.

D-CC, D-C++, Diab+, FastJ, pSOS+, SingleStep, Tornado, VxWorks, Wind River,and the Wind River logo are trademarks, registered trademarks, or service marksof Wind River Systems, Inc. Tornado patent pending.

APC and the APC logo are trademarks or registered trademarks of AmericanPower Conversion Corporation.

Other company, product or service names may be trademarks or service marks ofothers.

Notices C-3

Page 82: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

C-4 IBM Netezza Stored Procedures Developer's Guide

Page 83: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

Index

Special characters$var variable 2-6%, used in message formats 2-22%ROWTYPE attribute[ROWTYPE

attribute] 2-5%TYPE attribute[TYPE attribute] 2-5

Aaccount permissions, managing 3-1admin user, permissions 3-1aliases, for data types 2-9ALTER PROCEDURE command A-1

using 3-10ANY keyword 3-6ANY keyword, for procedure input

arguments 3-6arithmetic evaluations, and stored

procedures 2-12array variables

assigning a value 2-10in NZPLSQL 2-10reference support 2-10

assignment statement 2-15AUTOCOMMIT ON blocks 2-3

Bbackups, and stored procedures 1-6BEGIN_PROC keyword 1-5best practices, stored procedures 1-3block comments 2-4block quoting support 1-5block structured language 2-1block, in NZPLSQL 2-1

CCALL command

discarding results 2-16example 3-10usage A-3

call recursion limit 2-16casting

impact on stored procedures 2-12input values to match signature

sizes 3-6COMMENT ON PROCEDURE command,

using 3-11comments

best practices 3-11in NZPLSQL 2-4

conditional control 2-17CONSTANT option, variables 2-5constants, in NZPLSQL 2-5control statements

conditional 2-17IF-THEN statements 2-17iterative 2-19

control structures 2-17COUNT method, array variables 2-10CREATE OR REPLACE PROCEDURE

command A-5generic arguments example 3-7using 3-4

cross-database access, to storedprocedures 1-4

Ddata types 2-9DEBUG messages 2-22declarations section, in NZPLSQL 2-1DEFAULT clause, variables 2-5disk space problems, avoiding for large

datasets 2-27double dash comments 2-4downgrade cautions 1-7DROP PROCEDURE command A-7

using 3-12dropping when database is dropped 1-6dynamic queries 2-16

EELSE IF statements 2-17ELSIF statements 2-17END_PROC keyword 1-5error handling, in NZPLSQL 2-23errors, raising 2-22EXCEPTION messages 2-22EXCEPTION statement 2-23EXEC command, using 3-10execute as caller permissions 1-3execute as owner permissions 1-3EXECUTE command A-3

using 3-10EXECUTE IMMEDIATE statement 2-16EXECUTE PROCEDURE command,

using 3-10EXIT statement 2-19expressions

in NZPLSQL 2-11string processing best practices 2-16

EXTEND method, array variables 2-10

FFOR IN loop statement 2-21FOR loop, iteration step count 2-19FOR statement 2-19FOR-IN EXECUTE statement 2-21fully-qualified object names, for stored

procedures 1-4

Ggeneric arguments, benefits of 3-6

generic proceduresANY keyword 3-6input arguments 3-6registering 3-7

generic return value 3-7GRANT ALL command, create

permission 3-1GRANT command

alter permission 3-1create permission 3-1drop permission 3-1execute permission 3-1

Hhiding the procedure body 3-8

IIF statements 2-17IF-THEN-ELSE IF statements 2-17IF-THEN-ELSE statements 2-17implicit casting

for procedure input values 3-6in assignments 2-15in stored procedures, best

practices 2-12infinite loop, handling 2-28iterative control 2-19

Llabels, used to identify variables 2-7large datasets, managing 2-27LAST_OID variable 2-17loop processing 2-28LOOP statement 2-19loops

infinite, handling 2-28iterate over integer count 2-19repeating while true 2-19terminating 2-19unconditional 2-19

Mmassively parallel processing (MPP),

designing procedures for 2-28message levels, types of 2-22messages, reporting 2-22

NNetezza SQL commands

for stored procedures 1-2reference A-1

NOT NULL option, variables 2-5NOTICE messages 2-22

© Copyright IBM Corp. 2009, 2014 X-1

Page 84: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

NzAdmin administrative interface, forstored procedures 3-12

NZPLSQL languageabout 1-2array variables 2-10comments 2-4constants 2-5control structures 2-17description of 2-1dynamic queries 2-16exception support 2-23expressions 2-11message and error reporting 2-22procedural logic 1-2record assignments 2-20record variable 2-20records 2-20statements 2-15variable datatypes 2-5variables 2-5

Oobfuscating procedures

using in registration scripts 3-9using wrap_nzplsql 3-8

outputsALTER PROCEDURE command A-1CREATE OR REPLACE PROCEDURE

command A-5DROP PROCEDURE command A-7SHOW PROCEDURE command A-9

overflows, avoiding in storedprocedures 2-12

overloading procedures 3-5owner, stored procedure 3-1

Pparameters 2-6patches, and stored procedures 1-7PATH SQL session variable 1-4permissions 3-1

grantingall 3-1alter permission 3-1create 3-1drop permission 3-1execute permission 3-1

managing 3-1revoking

create permission 3-1drop permission 3-1execute permission 3-1

PL/pgSQL language 1-2privileges, commands

ALTER PROCEDURE command A-1CALL or EXECUTE PROCEDURE

command A-3CREATE PROCEDURE

command A-5privileges, managing for accounts 3-1PROC_ARGUMENT_TYPES array 2-6procedural programming language 1-1procedures

calling 2-16

procedures (continued)obfuscating 3-8returning from 2-17

Qquote_ident function 2-16quote_literal function 2-16

RRAISE statement 2-22RECORD variable 2-20records

about 2-20assignments 2-20

recursion limit, calls 2-16registration script, with obfuscated

procedures 3-9restores, and stored procedures 1-6RETURN command 2-17return value, generic 3-7REVOKE command

alter permission 3-1drop permission 3-1

revokingalter permission 3-1

ROLLBACK, using withREFTABLE 2-27

ROW_COUNT variable 2-17

Sscoping, variables 2-7SHOW PROCEDURE command A-9

using 3-12signature

about 3-5used in permissions 3-1

SQL commands, for storedprocedures A-1

SQLERRM variable 2-23statements

assignment 2-15in NZPLSQL 2-15section, in NZPLSQL 2-1

stored procedures 1-4, 1-6about 1-1account permission overview 3-1altering 3-10, A-1benefits of 1-1best practices 1-3block quoting support 1-5call recursion limit 2-16calling, starting 3-10commenting on 3-11creating 1-3, 3-4creating or replacing A-5designing 3-4displaying information for 3-12dropping 3-12, A-7example use of 1-1fully qualified name of 1-4generic, registering 3-7impact of implicit casting 2-12input 1-2

stored procedures (continued)limitations of size-specific input

arguments 3-5loop processing 2-28managing 3-1math best practices 2-12obfuscating the body 3-8owner of 3-1PATH session variable 1-4process to create 3-4return types 1-2run 1-3security and access controls 1-1security considerations 1-3See also procedures. 1-1showing A-9signature 3-5starting

CALL A-3using EXECUTE A-3

stored proceduresresult sets 1-2

user of 3-1strings, processing in expressions 2-16

Ttransaction commits in stored

procedures 2-2TRIM method, array variables 2-10

Uunconditional loop 2-19upgrades, and stored procedures 1-7

VVARARGS keyword 2-6, 3-7variable arguments, benefits of 3-7variable scoping 2-7variables

datatypes 2-5in NZPLSQL 2-5

WWHILE statement 2-19wrap_nzplsql built-in procedure 3-8

X-2 IBM Netezza Stored Procedures Developer's Guide

Page 85: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des
Page 86: IBM Netezza Stored Procedures Developer's Guide · International Business Machines Corp. New Orchard Road Armonk, New York 10504 914-499-1900 Der verantwortliche Ansprechpartner des

����

Part Number: 20470-05 Rev. 1

Printed in USA