
f95ccb2196b1b6c4354e288d707fe8cb.ppt
- Количество слайдов: 55
Database Programming Sections 1 & 2 – Case and Character Manipulations, number functions, date functions, conversion functions, general functions, conditional expressions, Null functions Marge Hohly
DUAL function o o The DUAL table has one row called "X" and one column called "DUMMY. “ The DUAL table is used to create SELECT statements and execute commands not directly related to a specific database table. Marge Hohly 2
Single Row Functions o o Single row functions are very powerful predefined code that accepts arguments and returns a value. An argument can be defined as a column name, an expression, or a constant. There are five single row functions groups: n n n Character Date General Number Conversion Marge Hohly 3
Single Row Functions o Single-row character functions are divided into two categories: n n o functions that convert the case of character strings functions that can join, extract, show, find, pad, and trim character strings. Single-row functions can be used in the SELECT, WHERE, and ORDER BY clauses. Marge Hohly 4
Single Row Functions o Character Functions (Case manipulation) n n n LOWER converts character strings to all lower case. SELECT last_name FROM employees WHERE last_name = ‘king’ WHERE LOWER(last_name) = ‘king’ (should be this way) UPPER converts character strings to all upper case. INITCAP converts the first letter of each word to upper case and the remaining letters to lower case. Marge Hohly 5
DUAL examples o o o SELECT LOWER('Marge') FROM dual; SELECT UPPER(‘Hello’) FROM dual; SELECT SYSDATE FROM dual; Marge Hohly 6
LOWER examples o Create a query that outputs the CD titles in the DJ on Demand database in all lowercase letters. SELECT LOWER(title) FROM d_cds; o Create a query that selects the first names of the DJ on Demand clients who have an "a" somewhere in their name. Output the results set in all uppercase letters. Ask students why UPPER was put in the SELECT statement and not in the WHERE clause. SELECT UPPER(first_name) FROM d_clients WHERE first_name LIKE '%a%'; Marge Hohly 7
Character Functions o Character Functions (Case manipulation) Function Result LOWER (‘I Love SQL’) i love sql UPPER (‘I love SQL’) I LOVE SQL INITCAP(‘I Love SQL’) I Love Sql Marge Hohly 8
Using LOWER, UPPER & INITCAP o o Use LOWER, UPPER, & INITCAP in SELECT statement to affect the output of the data Use in WHERE & ORDER BY to determine how data is chosen not displayed SELECT last_name, job_id FROM employees WHERE LOWER(job_id) = ‘it_prog‘; SELECT UPPER(last_name), job_id FROM employees; Marge Hohly 9
Character Functions o Character Functions (Case manipulation) n CONCAT joins two values together. n SUBSTR extracts a string of characters from a value. n LENGTH shows the length of a string as a numeric value. n LPAD/RPAD pads specified character to the left or right. n TRIM trims leading, trailing, or both characters from a string. n REPLACE replaces a string of characters. Marge Hohly 10
Single Row Functions o Character Functions (Case manipulation) Function Result CONCAT(‘ABC’, ‘DEF’) ABCDEF SUBSTR(‘ABCDEF’, 2, 3) BCD LENGTH(‘ABCDEF’) INSTR(‘ABCDEF’, ’C’) 6 3 Marge Hohly 11
Try these o o o SELECT SUBSTR(hire_date, 2, 4) FROM employees; SELECT LENGTH(last_name), last_name FROM employees; SELECT LPAD(SUBSTR(‘ 123 -568901’, 11, ’*’) FROM dual; Marge Hohly 12
Single Row Functions o Character Functions (Case manipulation) Function Result LPAD (salary, 9, ’*’) ****15000 RPAD (salary, 9, ’*’) 15000**** TRIM (leading ‘A’ from ‘ABC’) BC REPLACE(‘ABC’, ’B’, ’*’) A*C trailing or both Marge Hohly 13
Try These o o SELECT LPAD(salary, 9, '*') FROM employees; SELECT TRIM(trailing 'a’ from 'abbba') FROM dual; SELECT TRIM(both 'a’ from 'abbba') FROM dual; SELECT REPLACE('ABC', 'B', '*') FROM dual; Marge Hohly 14
Single Row Functions o Number Functions n n n ROUND rounds a value to specified position. TRUNC truncates a value to a specified position. MOD returns the remainder of a divide operation. o SELECT ROUND(45. 927, 2), ROUND(45. 927, 0), ROUND(45. 927), ROUND(45. 927, -1) FROM dual; o SELECT TRUNC(45. 927, 2), TRUNC(45. 927, 0), TRUNC(45. 927, -1) FROM dual; o SELECT MOD(600, 500) FROM dual; Marge Hohly 15
Single Row Functions o Working with Dates n n n the default display and input format for any date is DD-MON-RR. For example: 12 -OCT-05 (more on RR later) SYSDATE is a date function that returns the current database server date and time. the Oracle database stores dates in an internal numeric format. Which means arithmetic operations can be performed on dates. Marge Hohly 16
Examples o o SELECT (SYSDATE - hire_date)/7 AS "No. of Weeks“ FROM employees; SELECT MONTHS_BETWEEN(SYSDATE, '01 Jan-87') AS "no. of months“ FROM dual; SELECT ROUND(MONTHS_BETWEEN(SYSDATE, '01 Jan-87'), 2) AS "no. of months“ FROM dual; SELECT NEXT_DAY('01 -Sep-95', 'Friday') FROM dual; Marge Hohly 17
Date Functions Description months_between # of months between 2 dates add_months Add calendar months to date next_day Next day of the date specified (like Friday) last_date Last day of month (date) ROUND Round date TRUNC Truncate date Marge Hohly 18
Single Row Functions o Working with Dates (a few examples) n n n SELECT last_name, hire_date + 60 AS "Review Date“ FROM employees; SELECT last_name, (SYSDATE-hire_date)/7 FROM employees; SELECT order_no, amt_due, purch_date + 30 AS "Due Date“ FROM transactions; Marge Hohly 19
Single Row Functions o Date Functions n n n MONTHS_BETWEEN returns the number of months between two dates. ADD_MONTHS adds a number of months to a date. NEXT_DAY returns the date of the next specified day of the week. LAST_DAY returns the date of the last day of the specified month. ROUND returns the date rounded to the unit specified. TRUNC returns the date truncated to the unit specified. Marge Hohly 20
Single Row Functions o Date Functions (a few examples) Functions Result MONTHS_BETWEEN(’ 01 -SEP 15 -92’, ’ 01 -JUN-91’) ADD_MONTHS (’ 11 -JAN 94’, 6) ’ 11 -JUL-94’ NEXT_DAY(’ 01 -SEP 95’, ’FRIDAY’) ‘ 08 -SEP-95’ LAST_DAY(’ 01 -FEB-95’) ’ 28 -FEB-95’ Marge Hohly 21
Single Row Functions o Date Functions (a few more examples) n “Assume SYSDATE = ’ 25 -JUL-95’ Function Result ROUND(SYSDATE, ’MO ’ 01 -AUG-95’ NTH’) ROUND(SYSDATE, ’YE AR’) ’ 01 -JAN-96’ TRUNC(SYSDATE, ’MO NTH’) ’ 01 -JUL-95’ TRUNC(SYSDATE, ’YEA ’ 01 -JAN-95’ R’) Marge Hohly 22
Date Types Data Type conversion Implicit data type conversion Explicit data type conversion Marge Hohly 23
Implicit Data Type Conversion o For assignments, the Oracle serve can automatically convert the following: From To VARCHAR 2 or CHAR NUMBER VARCHAR 2 or CHAR DATE NUMBER VARCHAR 2 DATE VARCHAR 2 Marge Hohly 24
Explicit Type Conversion TO_NUMBER TO_DATE CHARACTER TO_CHAR DATE TO_CHAR Marge Hohly 25
Using the TO_CHAR Function with Dates o The format model: n n Must be enclosed in single quotation marks and is case sensitive Can include any valid date format element Has an fm element to remove padded blanks or suppress leading zeros Is separated from the date value by a comma Marge Hohly 26
Elements of the Date Format Model o YYYY YEAR MM MONTH MON o DY o o o DAY DD o o o o Full year in numbers Year spelled out Two-digit value for month Full name of the month Three-letter abbreviation of the day of the week Full name of the day of the week Numeric day of the month Marge Hohly 27
Examples of Date formatting o Date conversion to character data n n June 19 th, 2004 TO_CHAR(hire_date, 'Month ddth, YYYY') January 1, 2000 TO_CHAR(hire_date, 'fm. Month dd, YYYY') MAR 5, 2001 TO_CHAR(hire_date, 'fm. MON dd, YYYY') June 17 th Wednesday Nineteen Eighty. Seven TO_CHAR(hire_date, 'Month ddth Day Yy. YYSP') Marge Hohly 28
Examples o Using the current SYSDATE display it in the following format n n August 6 th, 2004 August 06, 2004 AUG 6, 2004 August 6 th, Friday, Two Thousand Four Marge Hohly 29
Using Date Format o SELECT employee_id, TO_CHAR(hire_date, 'MM/YY') Month_Hired FROM employees WHERE last_name = 'Higgins'; EMPLOYEE_ID MONTH_HIRED 205 06/94 Marge Hohly 30
Elements of the Date Format Model o Time elements format the time portion of the date. HH 24: MI: SS AM o Add character strings by enclosing them in double quotation marks. DD “of” MONTH o 15: 45: 32 PM 12 of OCTOBER Number suffixes spell out numbers. Ddspth fourteenth Marge Hohly 31
Using the TO_CHAR Function with Dates n SELECT last_name, TO_CHAR(hire_date, 'fm. DD Month YYYY') AS HIREDATE FROM employees; LAST_NAME HIREDATE King 17 -Jun-87 Kochhar 21 -Sep-89 De Haan 13 -Jan-93 Hunold Ernst Lorentz Mourgos 3 -Jan-90 21 -May-91 7 -Feb-99 16 -Nov-99 . . 20 Marge Hohly 32
Using the TO_CHAR Function with Numbers o TO_CHAR (number, ‘format_model’) These are some of the format elements you can use with the TO_CHAR function to display a number value as a character: 9 Represents a number 0 Forces a zero to be displayed $ Places a floating dollar sign L Uses the floating local currency symbol . Prints a decimal point , Prints a thousand indicator B Display zero values as blanks not 0 Marge Hohly 33
Number conversions to Character (VARCHAR 2) o Can you identify the format models used to produce the following output? n n $3000. 00 4, 500 9, 000. 00 0004422 Marge Hohly 34
Using the TO_CHAR Function with Numbers o SELECT TO_CHAR(salary, '$99, 999. 00') SALARY FROM employees WHERE last_name = 'Ernst‘; SALA R Y $6, 00 0. 0 0 Marge Hohly 35
Using the TO_NUMBER and TO_DATE Functions o Convert a character string to a number format using the TO_NUMBER function: TO_NUMBER(char[, ‘format_model’]) o Convert a character string to a date format using the TO_DATE function: TO_DATE(char[, ‘format_model’]) o These functions have a fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function Marge Hohly 36
Using fx modifier o Use the fx modifier to format dates exactly as follows n n o June 19 2004 July 312004 Format your birth date use DUAL n Example June 19, 1990 Marge Hohly 37
RR Date Format-dates over 2 centuries Current Date Specified Date RR Format YY Format 1995 27 -OCT-95 1995 27 -OCT-17 2017 1917 2006 27 -OCT-17 2017 2006 27 -OCT-95 1995 2095 If the specified two-digit year is: 0 -49 If two digits of the current year are: 0 -49 50 -99 The return date is in the current century The return date is in the century before the current one The return date is in the century after the current one The return date is in the current century Marge Hohly 38
Example of RR Date Format o o To find employees hired prior to 1990, use the RR format, which produces the same results whether the commands is run in 1999 or now: SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY') FROM employees WHERE hire_date < TO_DATE('01 -Jan-90', 'DD-Mon-RR'); LAST_NAME TO_CHAR(HIRE_DATE, 'DD-MON-YYYY') King 17 -Jun-87 Kochhar 21 -Sep-89 Whalen 17 -Sep-87 Marge Hohly 39
Try this o SELECT last_name, hire_date, TO_CHAR(hire_date, 'DD-Mon-RRRR') FROM employees WHERE TO_DATE(hire_date, 'dd-mon -RR') < '01 Jan 1999‘ Marge Hohly 40
YY and RR o SELECT TO_CHAR(TO_DATE(hire_date, 'DDMon-RR'), 'DD Mon YYYY') AS "RR Example“ FROM employees; RR Example 17 Jun 1987 21 Sep 1989 13 Jan 1993 o SELECT TO_CHAR(TO_DATE(hire_date, 'DD-Mon. YY'), 'DD Mon YYYY') AS "YY Example“ FROM employees YY Example 17 Jun 2087 21 Sep 2089 13 Jan 2093 Marge Hohly 41
2. 1. 14 & 2. 1. 15 Examples 2. Convert January 3, 2004, to the default date format 03 -JAN-04. 4. Convert today's date to a format such as: "Today is the Twentieth of March, Two Thousand Four“ 8. Create one query that will convert 25 -DEC-04 into each of the following (you will have to convert 25 -DEC -04 to a date and then to character data): n December 25 th, 2004 n DECEMBER 25 TH, 2004 n december 25 th, 2004 Marge Hohly 42
Nested Functions o o Nesting is allowed to any depth Evaluate from the inside out Marge Hohly 43
Null Functions o Null is unavailiable, unassigned, unknown, or inapplicable. n n NVL 2 NULLIF COALESCE Marge Hohly 44
NVL FUNCTION o o o NVL function converts a null value to a date, a character, or a number. The data types of the null value column and the new value must be the same. NVL (value that may contain a null, value to replace the null) can be used to convert column values containing nulls to a number before doing calculations. When arithmetic calculation is performed with null, the result is null. Marge Hohly 45
NVL FUNCTION examples o o SELECT NVL(auth_expense_amt, 0) FROM d_partners; SELECT NVL(hire_date, '01 -JAN-97') FROM employees SELECT NVL(specialty, 'None Yet') FROM d_partners; SELECT first_name, last_name, NVL(auth_expense_amt, 0) * 1. 05 AS Expenses FROM D_Partners; Marge Hohly 46
NVL 2 FUNCTION o o NVL 2 (expression 1 value that may contain a null, expression 2 value to return if expression 1 is not null, expression 3 value to replace if expression 1 is null) SELECT last_name, salary, NVL 2(commission_pct, salary + (salary * commission_pct), salary) income FROM employees; Marge Hohly 47
NULLIF FUNCTION o o o NULLIF function compares two functions. If they are equal, the function returns null. If they are not equal, the function returns the first expression. The NULLIF function is: NULLIF(expression 1, expression 2) SELECT first_name, LENGTH(first_name) "Expression 1", last_name, LENGTH(last_name) "Expression 2", NULLIF(LENGTH(first_name), LENGTH(last_name)) AS "Compare Them“ FROM D_PARTNERS; Marge Hohly 48
COALESCE FUNCTION o o o The COALESCE function is an extension of the NVL function, except COALESCE can take multiple values. If the first expression is null, the function continues down the line until a not null expression is found. If the first expression has a value, the function returns the first expression and the function stops. Marge Hohly 49
DP 2. 10. 2, 4 2. Not all Global Fast Foods staff members receive overtime pay. Instead of displaying a null value for these employees, replace null with zero. Include the employee's last name and overtime rate in the output. Label the overtime rate as "Overtime Status. " 4. Not all Global Fast Foods staff members have a manager. Create a query that displays the employee last name and 9999 in the manager ID column for these employees. Marge Hohly 50
Conditional Expressions o o Provide the use of IF-THEN-ELSE logic within a SQL statement Use two methods: n n CASE expressions DECODE function Marge Hohly 51
CASE Function – when – then - else o Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement: SELECT last_name, job_id, salary, CASE job_id WHEN 'IT_PROG' THEN 1. 10*salary WHEN 'ST_CLERK' THEN 1. 15*salary WHEN 'SA_REP' THEN 1. 20*salary ELSE salary END "REVISED_SALARY“ FROM employees; Marge Hohly 52
DECODE Function o Facilitates conditional inquires by doing the work of a CASE or IF_THEN_ELSE statement: SELECT last_name, job_id, salary, DECODE(job_id, 'IT_PROG', 1. 10*salary, 'ST_CLERK', 1. 15*salary, 'SA_REP', 1. 20*salary, salary) "REVISED_SALARY“ FROM employees; Marge Hohly 53
DECODE Example SELECT last_name, salary, DECODE (TRUNC(salary/2000, 0), 0, 0. 00, 1, 0. 09, 2, 0. 20, 3, 0. 30, 4, 0. 40, 5, 0. 42, 6, 0. 44, 0. 45) TAX_RATE FROM employees WHERE department_id = 80; Monthly Salary Range Rate $0. 00 – 1999. 99 00% $2, 000. 00 – 3, 999. 99 09% $4, 000. 00 – 5, 999. 99 20% $6, 000. 00 – 7, 999. 99 30% $8, 000. 00 – 9, 999. 99 40% $10, 000. 00 – 11, 999. 99 42% $12, 200. 00 – 13, 999. 99 44% $14, 000. 00 or greater 45% Marge Hohly 54
2. 3. 5 Practice 1. For each Global Fast Foods promotional menu, display the event name, and calculate the number of months between today and the ending date of the promotion. Round the months to a whole number. Label the column "Past Promos. " 2. Use the Oracle database to write a query that returns the salary for employee 174 as: Ellen Abel earns $11000. 00 monthly but wants $14000. 00 Marge Hohly 55
f95ccb2196b1b6c4354e288d707fe8cb.ppt