Your SlideShare is downloading. ×
1/30/2002 Staff Development Session 2002.03
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

1/30/2002 Staff Development Session 2002.03

185
views

Published on


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
185
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Introduction Database Analyst - duties include teaching class Relational Databases since 1987, mostly DB2 and Oracle
  • Cheryl’s email: What the hell are scalar functions? You probably have used some of these, even if you’re not familiar with the name. Operate on a single value May be column or expression, including the result of another scalar or columnar function, can be stacked
  • For each function, the first line shows the syntax. When the string is fixed length, or when you supply a length argument, the substring returned is a fixed length. If no length is specified and the string is variable, the result returned is a variable length string. You need to consider this when you define a host variable.
  • Length of a character string is more useful when using variable length columns. I didn’t find any varchar columns in our mainframe sasi db, but we would get the actual length of the data. In a cobol program, the length of a variable length column is automatically returned in a host variable anyway, but it can be useful in spufi or qmf. For example, if you have a comments column of 254 bytes, you may not have room to print the longest comments in a report. By querying that column for comments over say 50 or 100 characters, you could get an idea how many rows have lengthy comments and how effective it would be to truncate them.
  • Here is a case where we have used a function in the where clause – it will cost us some performance.
  • Removes leading and/or trailing characteres. Blanks are assumed unless specified otherwise. Useful combined with length function, as you will now get the length of string actually used in a fixed length character column.
  • Although we probably won’t ever use the HEX function in a COBOL program, it can be a useful debugging tool in spufi or qmf.
  • If you want to insure that the result is not null, the last expression should be either a literal or a column or expression that you know will never be null. This function is especially valuable in a program that accesses columns of numeric data that may contain nulls. If an arithmetic expression refers to a column containing a null value, the result of the expression will be null. You can insure against this by using COALESE to substitute zero for any null value found. It is also useful when selecting columns that may be null into host variables in a COBOL program. When I forgot to check the null indicator for the column “leavedate”, I was getting the leavedate of the last student who had one. Tried to correct by selecting coalesce(leavedate, ‘ ‘). This gave an SQL error saying wrong data type. Data types of arguments have to match. I could coalesce leavedate with a hard-coded date but I didn’t want that. Coalesce(char(leavedate),’ ‘) gave me the result I wanted.
  • This function allows the conversion of an unwanted value to a null. Not useful in COBOL, since it doesn’t recognize null values, but in another language, such as C++ or Java, you may want to convert zero values to null. Might use it if your database defaulted character columns to spaces when there is no data, but your coding language handled nulls.
  • First argument names the item Second argument identifies the desired format. DB2 generally defaults to the ISO format, unless your shop has customized the general default.) What is our default?? CHAR can also convert numbers to character strings. Similar to DIGITS, only it includes the decimal place and sign. ISO = International Standards Organization USA = IBM American Standard EUR = IBM European Standard JIS = Japanese Industrial Standard LOCAL = site specific
  • Keep in mind that if you are fetching dates into a COBOL program, and later want to compare them with other dates, you definitely want the ISO format. For LOCAL to work, the site must have an exit routine for date and time installed on the system, to return the value in the desired format. ---------+---------+---------+---------+---------+---------+---------+--------- select char(enterdate,local) from ssasipit.astu_student where ccsd_id = '357000'; ---------+---------+---------+---------+---------+---------+---------+--------- DSNT408I SQLCODE = -185, ERROR: THE LOCAL FORMAT OPTION HAS BEEN USED WITH A DATE OR TIME AND NO LOCAL EXIT HAS BEEN INSTALLED
  • A positive number could be used when comparing dates. Will see an example of this with the DAYS function.
  • Note – microseconds are set to zero
  • Can determine the days between two dates. First example - difference between two dates. Second example - age of an invoice. This is a lot easier than calculating in a cobol program, taking into consideration month lengths and leap year! You might call a date routine, but using this function in the select stmt could avoid calling another program.
  • Note in the example that digits to the right of the decimal point are truncated, not rounded. See the Integer example for a method of rounding. (Oracle has a round function.)
  • I think this would be used for double-byte character languages such as Arabic or Japanese characters.
  • Transcript

    • 1. DB2 Scalar Functions Pam Odden
    • 2. Objectives
      • Learn what a Scalar Function is
      • Where they can be used and what effect scalar functions have on performance
      • What scalar functions are available in DB2 Versions 4 and 5
    • 3. Definition
      • Scalar Functions: functions that operate on a single value, and may be applied to a column or expression. The result is a transformed version of the column or expression.
      • These are in contrast to Column Functions , which are applied to a set of data.
      • Scalar: (accding to Webster’s Dictionary) adj. Designating a quantity that has magnitude but no direction in space, such as volume or temperature.
    • 4. Use of Scalar Functions
      • Can be used in SELECT clause and WHERE or HAVING clause
      • In SELECT clause there is usually no effect on performance
      • In WHERE or HAVING clause, performance can be slowed. Scalar functions do not use indexes.
    • 5. Functions that transform Character Strings SUBSTR
      • SUBSTR(string,start[,length])
      • Returns a specified portion of a character string
      • String is a character or graphic string.
      • Start is the starting position of the substring. It must be a number between 1 and the length of the string.
      • Length is the total length of the substring. If length is omitted, the remainder of the string is returned.
        • select leavecode
        • , substr(leavecode,1,2) FIRST_TWO_CHAR
        • , substr(leavecode,3) THIRD_CHAR
        • from ssasidb1.astu_student
        • where ccsd_id = '357000';
        • ---------+---------+---------+---------+---------+
        • LEAVECODE FIRST_TWO_CHAR THIRD_CHAR
        • ---------+---------+---------+---------+---------+
        • W1B W1 B
    • 6. SUBSTR (cont.)
      • Our book gives a slick example of using substr to get last name, first initial. It assumes that lastname is a variable-length column (VARCHAR). In SASI, and probably most of our databases, names are fixed length, which will give the second result. See the example of the STRIP function (available in v. 5) for the desired result.
      • Select lastname || ', ' || substr(firstname,1,1) || '.'
      • As LNAME_FI
      • from ssasidb1.astu_student
      • where schoolnum = '201';
      • ---------+---------+---------+---------+---------+---------+
      • LNAME_FI
      • ---------+---------+---------+---------+---------+---------+
      • RAGNETTI, A.
      • SMITH, B.
      • What I really got in SPUFI:
      • ---------+---------+---------+---------+---------+---------+
      • LNAME_FI
      • ---------+---------+---------+---------+---------+---------+
      • RAGNETTI , A.
      • SMITH , B.
    • 7. LENGTH
      • LENGTH(expression)
      • Returns the length of any column, including leading or trailing blanks or zeros, as an integer.
      • The null indicator byte is not counted.
      • In strings, spaces are counted, but the length control field of a variable-length string is not counted.
      • Length returned is the number of bytes required to store the data type
        • 2 for small integer
        • 3 for time
        • 4 for date and integer
        • 10 for timestamp
      •  
    • 8. LENGTH (cont.)
      • The length function could be used to determine how many characters of a variable length column are actually used. Say you are formatting a report and you’d like to truncate the teacher_comment column, varchar(256). You could find the longest comment:
      •  
      • select max(length(teacher_comment)) as LONGEST_COMMENT
      • from ssasidb1.astu_student;
      • LONGEST_COMMENT
      • 170
      •  
      • If you only have room for 150 characters, you could find out how many students have comments that would be truncated:
      • select count(*) NBR_LONG_COMMENTS
      • from ssasidb1.astu_student
      • where length(teacher_comment) > 150;
      • NBR_LONG_COMMENTS
      • 17
    • 9. STRIP (version 5)
      • STRIP(expression,L/T,strip character)
      • Removes leading and/or trailing characters from expression
      • L/T may be L, LEADING, B, BOTH, T, TRAILING
      • Strip character is the character to be removed
      • If L/T is omitted, BOTH is assumed
      • If strip character is omitted, space is assumed.
    • 10. Example using LENGTH and STRIP
      • select firstname NAME
      • , length(strip(firstname)) LENGTH_STRIPPED
      • from ssasipit.astu_student
      • where permnum in (' 1947',' 53268',' 93239');
      • ---------+---------+---------+---------+---------+---------
      • NAME LENGTH
      • ---------+---------+---------+---------+---------+---------
      • ELVIA 5
      • ALEXIS 6
      • ZACHARY 7
      •  
      • Select strip(lastname) || ', ' || substr(firstname,1,1) || '.'
      • As LNAME_FI
      • from ssasidb1.astu_student
      • where schoolnum = '201';
      •   ---------+---------+---------+---------+---------+---------+
      • LNAME_FI
      • ---------+---------+---------+---------+---------+---------+
      • RAGNETTI, A.
      • SMITH, B.
    • 11. HEX
      • HEX(expression)
      • Returns a hexidecimal character string representation of a value with 2 hexadecimal digits per byte.
      • If the expression is a graphic data item, the result will contain 4 hexadecimal digits for each character.
      • If the expression is null, the result will be null.
        • select hex(socsecnum) H_SOC
        • from ssasidb1.astu_student
        • where ccsd_id = ‘075160’;
        •  
        • H_SOC
        • ---------+---------+--
        • F5F9F5F3F5F6F9F5F540
    • 12. Functions that transform Null Values COALESCE (or VALUE)
      • COALESCE(expression1,expression2[,expression3…])
      • Returns the first expression in the list that is not null.
      • The first expression is evaluated and, if not null, it is returned.
      • If the first expression is null, the next is evaluated, and returned if not null.
      • If all expressions in the list are null, null is returned.
    • 13. COALESCE (cont.)
      • Select custno,
      • coalesce(‘H: ‘ || homephone,
      • ‘ W: ‘ || workphone,
      • ‘ NO PHONE NUMBER’) as PHONE
      • from customer_table
      • order by custno;
      •  
      •  
      • CUSTNO PHONE
      • 12345 H: 702-123-7859
      • 12346 W: 702-875-7890
      • 12347 H: 702-789-7543
      • 12349 NO PHONE NUMBER
    • 14. NULLIF (version 5)
      • NULLIF(expression1,expression2)
      • Returns null if the two expressions are equal, otherwise returns the first expression.
      • Expressions 1 and 2 must be compatible data types
      • Not often used with COBOL, but useful with a programming language that recognizes the null data type.
        • Select street || ‘ ‘ ||
        • nullif(po_box,’ ‘) || ’, ‘ ||
        • city || ‘, ‘ ||
        • state || ‘ ‘ ||
        • zip as ADDRESS
        • from customer_table;
        • ADDRESS
        • 126 Elm Street P.O. Box 123, Las Vegas, NV 89045
        • 4576 Flamingo Road, Las Vegas, NV 89222
    • 15. Functions that transform Dates CHAR
      • CHAR(expression[,format])
      • Returns a character representation of a date value
      • Expression can be a date, time, or timestamp
      • For date and time expressions, a format can be specified: ISO, USA, EUR, JIS, LOCAL.
      • DB2 generally defaults to the ISO format, unless your shop has customized the general default
        • ISO = International Standards Organization
        • USA = IBM American Standard
        • EUR = IBM European Standard
        • JIS = Japanese Industrial Standard
        • LOCAL = site specific (only works if coded for your site)
    • 16. CHAR (cont.)
      • Select current date as CURR_DATE
      • , Char(current date,ISO) as DATE_ISO
      • , char(current date,USA) as DATE_USA
      • , char(current date,EUR) as DATE_EUR
      • , char(current date,JIS) as DATE_JIS
      • from ssasidb1.astu_student
      • where permnum = ' 354678';
      •  
      • CURR_DATE DATE_ISO DATE_USA DATE_EUR DATE_JIS
      • 01/27/2002 2002-01-27 01/27/2002 27.01.2002 2002-01-27
      •  
      •  
      • Select current time as CURR_TIME
      • , Char(current time,ISO) as DATE_ISO
      • , char(current time,USA) as DATE_USA
      • , char(current time,EUR) as DATE_EUR
      • , char(current time,JIS) as DATE_JIS
      • from ssasidb1.astu_student
      • where permnum = ' 354678';
      •  
      • CURR_TIME TIME_ISO TIME_USA TIME_EUR TIME_JIS
      • 04:20 PM 16.20.34 04:20 PM 16.20.34 16:20:34
    • 17. DATE and TIME
      • DATE(expression)
      • TIME(expression)
      • Returns a date or time in default format
      • For DATE, expression can be a date, timestamp, a string representation of a date, or a positive number less than or equal to 3,652,059.
      • For TIME, expression can be a time, timestamp, or string representation of a time.
      • select current timestamp as TIMESTAMP,
      • date(current timestamp) as DATE,
      • rime(current timestamp) as TIME
      • from ssasidb1.astu_student
      • where permnum = ‘ 3456776’;
      •  
      • TIMESTAMP DATE TIME
      • 2002-01-28-09.06.46.940524 01/28/2002 09:06 AM
    • 18. TIMESTAMP
      • TIMESTAMP(expression1[,expression2])
      • Returns a timestamp.
      • When only 1 expression is used, it can be a timestamp or a string representation of a timestamp.
      • When 2 expressions are used, expression1 must be a date or string representation of a date and expression2 must be a time or string representation of a time.
      • select current date as DATE,
      • current time as TIME,
      • timestamp(current date, current time) as TIMESTAMP
      • from ssasidb1.astu_student
      • where permnum = ‘ 3456776’;
      •  
      • DATE TIME TIMESTAMP
      • 01/28/2002 09:09 AM 2002-01-28-09.09.42.000000
      •  
      • (Notice when the timestamp is selected from the database, it contains the microseconds. When it is created by the timestamp function, the microseconds are zero.)
    • 19. Components of Dates and Times
      • YEAR(expr) Expr can be a date, date
      • MONTH(expr) duration, timestamp, or
      • DAY(expr) timestamp duration.
      • HOUR(expr) Expr can be a time, time
      • MINUTE(expr) duration, timestamp, or
      • SECOND(expr) timestamp duration.
      • MICROSECOND(expr)
      • Each function returns the result as a binary fullword, PIC S9(9) COMP.
      • Select year(current date) as YEAR,
      • month(current date) as MONTH,
      • day(current date) as DAY,
      • hour(current timestamp) as HOUR,
      • minute(current timestamp) as MINUTE,
      • second(current timestamp) as SECOND,
      • microsecond(current timestamp) as MICROSECOND
      • from ssasidb1.astu_student
      • where permnum = ‘ 3456776’;
      •  
      • YEAR MONTH DAY HOUR MINUTE SECOND MICROSECOND
      • 2002 1 28 9 26 26 444084
    • 20. DAYS
      • DAYS(expression)
      • Returns the number of days that have elapsed between December 31, 0000 and the date of its argument
      • Useful for calculating the number of days between two dates
      • Expression can be a date, timestamp, or string that DB2 can interpret as a date
      • Result is a binary integer: PIC S9(9) COMP
      • Select days('2002-01-15') - days('2001-06-30') as DAYS_DIFFERENCE
      • From ssasidb1.astu_student
      • Where permnum = ' 489675';
      •  
      • DAYS_DIFFERENCE
      • 199
    • 21. DAYS (cont.)
      • Select ccsd_id, enterdatedate,
      • Days(enterdate) - days(‘08/30/2001’) as DAYS_LATE
      • From ssasidb1.astu_student
      • Order by DAYS_LATE desc;
      •  
      • CCSD_ID ENTERDATE DAYS_LATE
      • 313533 10/09/2001 40
      • 331177 10/08/2001 39
      • 301730 10/08/2001 39
      • 419779 10/04/2001 35
      • 192606 10/03/2001 34
    • 22. Functions that transform Numbers DECIMAL
      • DECIMAL(expression[,precision[,scale]])
      • Returns a decimal representation of the first argument.
      • Precision specifies the total number of digits
      • Scale specifies the number of digits to the right of the decimal point.
      • If precision or scale is omitted the result defaults to the precision or scale of the first argument.
      • A COBOL host variable is defined as COMP-3 and must contain the correct number of digits on both sides of the decimal point. If it does not, an SQL error –406 will be returned.
    • 23. DECIMAL (cont.)
      • (Note: the column credearned is defined in the ssasidb1 database as DECIMAL(7,3).)
      •  
      • ---------+---------+---------+---------+---------+------
      • Select credearned,
      • decimal(credearned,7,1) as DEC_7_1,
      • decimal(credearned,9,5) as DEC_9_5
      • From ssasidb1.astu_student where credearned <> 0
      • ---------+---------+---------+---------+---------+------
      • CREDEARNED DEC_7_1 DEC_9_5
      • ---------+---------+---------+---------+---------+------
      • .500 .5 .50000
      • 4.500 4.5 4.50000
      • 6.000 6.0 6.00000
      • 7.500 7.5 7.50000
      • 6.000 6.0 6.00000
      • 5.500 5.5 5.50000
      • 6.250 6.2 6.25000
      • .500 .5 .50000
      • 1.166 1.1 1.16600
    • 24. INTEGER
      • INTEGER(expression)
      • Returns the whole-number portion of expression, with any fractional portion truncated.
      • No rounding is performed.
      • A COBOL host variable is defined as PIC S9(9) COMP.
      • Select credearned,
      • integer(credearned) as INTEGER,
      • integer(credearned + .5) as ROUNDED_INTEGER
      • From ssasidb1.astu_student where credearned <> 0
      • ---------+---------+---------+---------+---------+------
      • CREDEARNED INTEGER ROUNDED_INTEGER
      • ---------+---------+---------+---------+---------+------
      • .500 0 1
      • 4.500 4 5
      • 6.000 6 6
      • 16.700 16 17
    • 25. FLOAT
      • FLOAT(expression)
      • Returns a double-precision floating point equivalent of expression.
      • Expression must be a number.
      • A COBOL host variable is be defined as COMP-2 with no PICTURE clause.
      • Select credearned,
      • float(credearned) as FLOAT
      • From ssasidb1.astu_student where credearned <> 0
      • ---------+---------+---------+---------+---------+-----
      • CREDEARNED FLOAT
      • ---------+---------+---------+---------+---------+-----
      • .500 +0.5000000000000000E+00
      • 4.500 +0.4500000000000000E+01
      • 6.000 +0.6000000000000000E+01
      • 7.500 +0.7500000000000000E+01
    • 26. DIGITS
      • DIGITS(expression)
      • Returns a character string of the digits in expression.
      • The result does not include a sign or a decimal point.
      • A COBOL host variable is defined as PIC X(n) where n is the length of the data type of expression.
      • Select credearned,
      • digits(credearned) as DIGITS
      • From ssasidb1.astu_student where credearned <> 0
      • ---------+---------+---------+---------+---------+------
      • CREDEARNED DIGITS
      • ---------+---------+---------+---------+---------+------
      • .500 0000500
      • 4.500 0004500
      • 6.000 0006000
      • 7.500 0007500
      • 6.000 0006000
    • 27. VARGRAPHIC
      • VARGRAPHIC(expression)
      • Returns a graphic string of the value of expression.
      • Used with double-byte character strings.
      • We will probably not use this in a COBOL program.
      • Select lastname,
      • vargraphic(lastname) as VARGRAPHIC
      • From ssasidb1.astu_student where schoolnum = '201';
      • ---------+---------+---------+---------+---------+-----
      • LASTNAME VARGRAPHIC
      • ---------+---------+---------+---------+---------+-----
      • ROBLES .âRâOâBâLâEâS
      • MAY .âMâAâY
      • MARCINKEVICH .âMâAâRâCâIâNâKâEâVâIâCâH
    • 28. Summary
      • Scalar functions may be used to retrieve data in the format needed and avoid some programming.
      • Consider performance when using scalar functions in a where clause, as no index will be used.
      • Not all of the available scalar functions are useful in COBOL programs, but most are a handy tool in SPUFI and other direct queries.