22BI Creating SQL Functions

Slides:



Advertisements
Similar presentations
SQL Rohit Khokher.
Advertisements

Makefiles. makefiles Problem: You are working on one part of a large programming project (e. g., MS Word).  It consists of hundreds of individual.c files.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
1 Inside Module 9 Latest Features in Suprtool n Variable Substitution n $Counter n $Clean and $FindClean n $Total and $Subtotal n $SPLIT n $EDIT n $NUMBER.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
FUNCTIONS AND STORED PROCEDURES & FUNCTIONS AND PROTECTING A DB AND PHP (Chapters 9, 15, 18)
OWASP Top Ten #1 Unvalidated Input. Agenda What is the OWASP Top 10? Where can I find it? What is Unvalidated Input? What environments are effected? How.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Oracle Data Integrator User Functions, Variables and Advanced Mappings
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
RPG free basics Session 1. RPG free Session 12 “C” Spec structure change Fixed Format Structure Factor 1OPCODEFactor 2Result Num1AddNum2Num3 EvalNum3=Num1+Num2.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Cosc 5/4765 Database security. Database Databases have moved from internal use only to externally accessible. –Organizations store vast quantities of.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Functions + Overloading + Scope
Chapter 7: Function.
31BI How to Use the SQL Descriptor
User-Written Functions
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
T-SQL: Simple Changes That Go a Long Way
Quiz Questions Q.1 An entity set that does not have sufficient attributes to form a primary key is a (A) strong entity set. (B) weak entity set. (C) simple.
Debugging and Random Numbers
Inside Module 10 Editing TurboIMAGE Datasets Page
Core LIMS Training: Advanced Administration
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
A First Book of ANSI C Fourth Edition
Functions CIS 40 – Introduction to Programming in Python
Microsoft Access Illustrated
Web Programming– UFCFB Lecture 17
Types of SQL Commands Farrokh Alemi, PhD
SQL – Procedures And Functions
Variables and Arithmetic Operations
DATABASE MANAGEMENT SYSTEM
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Phil Tayco Slide version 1.0 Created Oct 2, 2017
DB2.
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
JCL Standards #5 Company Name
SAS Essentials How SAS Thinks
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Andy Wang Object Oriented Programming in C++ COP 3330
A First Book of ANSI C Fourth Edition
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Using JDeveloper.
Part B – Structured Exception Handling
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Database systems Lecture 3 – SQL + CRUD
Lecture 12: SQL Friday, October 20, 2000.
SQL-1 Week 8-9.
Introduction of Week 11 Return assignment 9-1 Collect assignment 10-1
Index Note: A bolded number or letter refers to an entire lesson or appendix. A Adding Data Through a View ADD_MONTHS Function 03-22, 03-23,
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
String.
Loops.
Andy Wang Object Oriented Programming in C++ COP 3330
IST 318 Database Administration
Trainer: Bach Ngoc Toan– TEDU Website:
CPS125.
Lecture 14: SQL Wednesday, October 31, 2001.
T-SQL: Simple Changes That Go a Long Way
Presentation transcript:

22BI Creating SQL Functions Greg Cannella

Functions let you transform data from the way it is stored in the database to the way you want to use or see it.

Agenda Why functions? Examples Create function Drop function How to see and manage existing functions Handling NULL

Why functions? Fix the sins of your predecessors! Make SQL do new things Use complex routines Helps to keep SQL simple Simplify routine tasks

Examples Convert date from DB format to user format Select datemdy(dbdate) from xyzfile This example converts from 1151021 to 10/21/15

Examples Pricing Routines 1000s of lines of existing code Select price(customer,item,date) from xyzlist Create a stub service program that simply calls your existing code

Examples Create a hyper link <a href="https://google.com">Google</a> Select link(url,urltext) from websitelst -OR- select CONCAT(concat(Concat('<a href="',TRIM(url)), concat('">',TRIM(urltext))), '</a>') from websitelst

Built in Functions List of DB2 functions (just the common ones) Count, Min, Max, Sum, Char, CurDate, CurTime, Hex, Left, Length, Coalesce Substr, Day, Date, Lower, Upper, Right, Round, RRN, Trim Complete list of built in functions: http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc h2func.htm

Create Function Statement CRTSRVPGM SRVPGM(QGPL/DATEMDY) EXPORT(*ALL) Then STRSQL and run the following SQL command. create function LIBRARY.DATEMDY (cyymmdd numeric(7,0) default 0) returns char(8) language rpgle deterministic no sql external name ‘QGPL/DATEMDY(DATEMDY)' parameter style general

Unpacking the create function Parameters In this example: (cyymmdd numeric(7,0)) A single parm is passed into the function For multiple parms the syntax is: (dbname char(128), Parm2 char(10), Parm3 numeric(7,0)) Parameters go into the function but don’t come back.

Unpacking the create function Returns This needs to match the value coming back from the service program. This needs to match exactly. Also note that SQL data types can differ from RPG data types. If the type doesn’t match exactly, you will get a function not found error when trying to use the function.

Unpacking the create function Language You can use any language available on the platform to create functions These can have embedded SQL or not.

Unpacking the create function Deterministic Use ‘not deterministic’ if the same parameters might return different results. Example: The function returns the number of jobs waiting to run in a JOBQ. Use ‘deterministic’ if the function will always return the same value for the same values Example: The function accepts in a date and returns the day of the week.

Unpacking the create function SQL – Probably the most important. This needs to match how your function works. READS SQL DATA – Prevents the underlying function from modifying data in the database CONTAINS SQL – Allows a very limited set of “non-executable” SQL statements. NO SQL – The underlying function can’t run any SQL. MODIFIES SQL DATA – The underlying function can run SQL statements that updates, inserts, deletes, or reads data.

Unpacking the create function External name This is the name of the service program and module Syntax: library/Servicepgm(Module) Example: gregc/datemdy(datemdy)

Unpacking the create function Parameter style I just use ‘parameter style general’ These cause the parameters to function very much like RPGLE service programs. There is also SQL, DB2GENERAL, JAVA, DB2SQL.

Recap create function create function LIBRARY.DATEMDY (cyymmdd numeric(7,0) default 0) returns char(8) language rpgle deterministic no sql external name ‘QGPL/DATEMDY(DATEMDY)' parameter style general

Drop Function drop function library.datemdy

Managing Functions Navigator for I Navigate to the schema where your functions are stored Click on functions

Navigator for i Select a function Actions Definition This will allow you to see and modify everything about the function definition.

Handling Errors and NULL Check your parms upon entry Monitor for bad data Select a default value if failure Datemdy(coalesce(field1,0))

Function Not Found Error Check the library Check the spelling Check that the parameters match (Functions allow overloading.) 7.1 Doesn’t cast variables as well as 7.2. You may need to force type your parameters.

Recap Use functions to transform data Create function Drop function Navigator for managing functions

Thank you Questions?

For more info on functions Create functions http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc fsc.htm Built in functions http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc h2func.htm

Sample Convert Date Program ctl-opt option(*srcstmt:*nodebugio) Debug nomain alwnull(*usrctl) ; // Compile Options: * // Create this as a module. * // CRTSRVPGM SRVPGM(MAGID/DATEMDY) EXPORT(*ALL) * // Then start SQL and run the following SQL command. * // create function magid.DATEMDY * // (cyymmdd numeric(7,0) default 0) * // returns char(8) * // language rpgle * // deterministic * // no sql * // external name 'MAGID/DATEMDY(DATEMDY)' * // parameter style general * //--Entry Prototype dcl-pr DATEMDY char(8); DateIn zoned(7:0) OPTIONS(*NOPASS); end-pr; dcl-proc DATEMDY export ; dcl-pi DATEMDY char(8); end-pi; dcl-s WorkDate date(*iso); dcl-s DateOut char(8); //-- Convert date from CYYMMDD to MM/DD/YY c Eval DateOut = *blanks c Monitor c *cymd Move DateIn WorkDate c *mdy Move WorkDate DateOut c On-error c Endmon return DateOut; end-proc;

Don’t Forget Your Session Surveys Sign in to the Online Session Guide (www.common.org/sessions) Go to your personal schedule Click on the session that you attended Click on the Feedback Survey button located above the abstract Completing session surveys helps us plan future programming and provides feedback used in speaker awards. Thank you for your participation.