Oracle Database explain the one-way function

One-way function

6.1, recognizing one-way function

For developers, the most important is the SQL syntax and single function, but the number of single-row functions Oracle is very much. This chapter will explain the use of the back will explain how to develop your own function (PL / SQL Programming)

6.1.1 single-line function syntax

funcation_name (column | expression [, parameter 1, parameter 2,])

Function names (column | expression | value), and the book will explain the basic Oracle in some way function.

6.1.2 one-way function classification

  • Character functions: receiving return data specific character information
  • Numerical functions: digital processing, such as: rounding
  • Date function: Date directly related operations
  • Conversion functions: convert each function can be completed between dates, characters, numbers
  • General Functions: Functions Oracle provides a unique clause

6.2, character function

  • Certain data is the main character (string)
NO. Function name description
1 UPPER (column | string) The contents of the string all uppercase turn
2 LOWER (column | string) The contents of the string transfer all lowercase
3 INITCAP (column | string) The beginning of the string capitalized
4 REPLACE (column | strings, new strings) Use the new string to replace the old string
5 LENGTH (column | string) Determined string length
6 SUBSTR (column | string start point [, length]) String interception
7 ASCII (character) Returns the specified character corresponding to a decimal number
8 CHR (Digital) A given integer, and returns the character corresponding thereto
9 RPAD (column | string, length, padding characters)
LPAD (column | string, length, padding characters)
In the left or right padding size is specified
10 LTRIM (string), RTRIM (String) Remove the spaces left or right
11 TRIM (column | string) Remove about blank
12 INSTR (column | string, the string you want to find, the start position, the position appears) Look for a string that appears at the specified location on
  • Here there is a problem arises, in which all Oracle verification operation must be present in the complete SQL statement, so if we just functional verification, using a specific table.
scott 用户下:
SELECT UPPER('li xing hua') 
FORM emp;
  • This time the findings were repeated displays 14 lines, so now the performance function is indeed verified, but the price is too high. If you are using DISTINCT can be eliminated, so a lot of data, if emp table it? Then the amount of data mediation will be enormous, so now you want to have a table can help authenticate a user in Oracle where it provides a dual data table (virtual table).

Examples : Verify UPPER () and LOWER () function

SELECT UPPER('li xing hua'),LOWER('MLDN')
FORM dual;

Examples : employee names are now check out the complete information "smith", but by mistake, without taking into account sensitive issues, then you can use the UPPER () function to capitalize the entire contents.

SELECT * 
FORM emp
WHERE ename = UPPER('smith');

Examples : Query all employee names, the name of each employee's claim appear in uppercase first letter

SELECT ename 原始姓名,INITCAP(ename) 姓名开头首字母大写
FORM emp;

Examples : Query all employee information, employee name will be required in all of the letters "A" replaced with "_"

SELECT ename,REPLACE(ename,'A','_')
FORM emp;

Examples : find out the names of all employee information length is 5

SELECT * 
FORM emp
WHERE LENGTH(ename) = 5;

Examples : check out the names of former employees of three letters "JAM" of employee information

  • So now find a way out of the first three characters interception, interception operation to be sure to use the SUBSTR () function is to be noted that, SUBSTR () function takes two forms:
    • Taken from a specified position to the end: SUBSTR (column | string, the cutout start point)
    • Interception partial string: SUBSTR (column | number string, the starting point taken intercept)
SELECT * 
FORM emp
WHERE SUBSTR(ename,1,3) = 'JAM'; 

或者:

SELECT * 
FORM emp
WHERE SUBSTR(ename,0,3) = 'JAM';
  • Note: In Oracle, subscripts are from the beginning, if set to 0, it will automatically be converted to 1.

Examples : Query all 10 department employee name, but does not show the first three letters of the name of each employee

SELECT ename 原姓名,SUBSTR(ename,3) 截取之后的姓名 
FORM emp
WHERE deptno = 10;

Examples : displayed after each three-letter name and the names of employees

  • To intercept after each name among the three, the first problem to be solved is the starting point, from a specified start point to the end have been intercepted, but the length of the name of each employee is different, then the starting point to determine how it ?

    • Achieve a: using conventional practices to obtain the length of the name, and then determine the starting point of minus 2
    SELECT ename 原始姓名,SUBSTR(ename,LENGTH(ename) - 2) 截取之后的姓名  
    FORM emp
    WHERE deptno = 10;
    • Achieve two: In addition to such practices can also set the start point is negative
    SELECT ename 原始姓名,SUBSTR(ename,-3) 截取之后的姓名  
    FORM emp
    WHERE deptno = 10;
  • Now obviously the most convenient to use the second, this is also part of the Oracle features, but it needs to be noted that: a string subscript Java language, or start from zero, but in Java substring () method is not set negative.

  • Interview questions: Will Oracle in SUBSTR () function subscript starting point is from 0 or 1 to start?

    A: You can set to 0, can also be set to 1, even with 0, then the end result will be defined as 1.

Examples : Returns the ASCII code of the specified character

SELECT ASCII('A'),ASCII('L')
FORM dual;

Examples : Verify the CHR () function, the ASCII character back

SELECT CHR(100) FORM dual;

Examples : removing the string left blank - LTRIM (), remove the right space - RTRIM ()

SELECT '     MLDN    LiXingHua     ' 原始字符串,LTRIM('    ') 去掉左空格
FORM dual;

SELECT '     MLDN    LiXingHua     ' 原始字符串,RTRIM('    ') 去掉右空格
FORM dual;

Examples : remove about blank

SELECT '     MLDN    LiXingHua     ' 原始字符串,TRIM('    ') 去掉左右空格
FORM dual;
  • Regardless of how to cancel a space, in the middle of a space but can not be eliminated out.

Examples : string left filled - LPAD (), the string right padding - RPAD ()

SELECT LPAD('MLDN',10,'*') LPAD函数使用,RPAD('MLDN',10,'*') RPAD函数使用,
LPAD(RPAD('MLDN',10,'*'),16,'*') 组合使用 
FORM dual;

Example : search string - INSTR ()

SELECT 
    INSTR('MLDN Java','MLDN') 查找得到,
    INSTR('MLDN Java','Java') 查找得到,
    INSTR('MLDN Java','JAVA') 查找不到
FORM dual;
  • This function is in Java indexOf () method function is the same.
  • summary:
    • The main function is the function character string data of the operation

6.3, numerical functions

No. Function name description
1 ROUND (number [, decimals]) Decimal rounding, you can specify the number of bits reserved, if not specified, then all the numbers after the decimal point is rounded
2 TRUNC (number [intercept bits]) Preserve the specified number of decimal places, if not specified, it means no decimals
3 MOD (Number, Number) Modulo

Examples : Verify ROUND () function is used

SELECT 
    ROUND(789.652) 不保留小数,
    ROUND(789.652,2) 不保留小数,
    ROUND(789.652,-1) 不保留小数,
FROM dual;

Examples : list some basic information and circumstances of each employee's daily wage

  • For the calculation of the daily wage of 30 days may be adopted as the basis, there will certainly be a decimal, reserved 2
SELECT empno,ename,job,hiredate,sal,ROUND(sal/30,2) 日薪金
FROM emp;
  • The ROUND function () function is a binary decimal, and TRUNC () function is not binary.

Examples : Verify TRUNC () function is used

SELECT 
    TRUNC(789.652) 截取小数,
    TRUNC(789.652,2) 截取2位小数,
    TRUNC(789.652,-2) 取整
FROM dual;

Examples : MOD () function to verify, is to take over mold

SELECT MOD(10,3) FROM dual;

6.4 Date Functions

  • If you now want to carry out the operation date, it would certainly there is a premise, you must know the current date
  • Get the current system time, you can directly use the pseudo-column SYSDATE get the current date and time. Refers to the so-called pseudo-column is not listed in the table, but the column can be directly used.
SELECT empno,ename,SYSDATE FROM emp;
SELECT SYSDATE FROM dual;
  • Content displayed by default, contains only three elements year, month, day, if you want to display more content, you must modify the locale.
  • Modification date display formats:
    • Run - sqlplus / nolog - conn c ## scott / tiger
    • Enter the following code
ALTER SESSION SET NLS_DATE_FORMAT = 'yyyy-mm-dd hh24:mi:ss';
SELECT SYSDATE FROM dual;
  • Changing the date display format after you close the window will be restored reopened

  • In addition to the operating system to obtain time outside in Oracle has three operation date of the following formula:
    • Date - The date = number, represents a number of days before the date
    • = + Number Date date, several days after the date indicates
    • Date - The date digital = (number of days), the interval represents the number of days between two dates
  • But there is absolutely no calculation "date + date", following its verification.

SELECT 
    SYSDATE+3 三天之后的日期,
    SYSDATE-3 三天之前的日期
FROM dual;

Examples hired a few days to a few days of date of hire check out each employee, and the employee's day ten days ago:

SELECT empno 雇员编号, ename 雇员姓名, 
    SYSDATE-hiredate 雇佣天数, 
    (SYSDATE-10)-hiredate 10天前雇佣天数
FROM emp;
  • Results decimal, the decimal point can be intercepted by TRUNC ()
SELECT empno 雇员编号, ename 雇员姓名, 
    TRUNC(SYSDATE-hiredate) 雇佣天数, 
    TRUNC((SYSDATE-10)-hiredate) 10天前雇佣天数
FROM emp;
  • These are just operating at the current time, the case of Oracle, also provide the appropriate date functions, had used date functions, mainly to avoid a leap year problem, or a month 28,29,30,31-day problems, by date time calculation date functions achieved are the most accurate.
No. Function name description
1 ADD_MONTHS (dates, numbers) Adding the specified number of months on the specified date, to obtain a new date
2 The MONTHS_BETWEEN (Date 1, Date 2) Find the number of months between the two dates of employment
3 NEXT_DAY (date, week number) Calculated the exact date of the next week
4 LAST_DAY (date) Find the specified date where the date of the last day of the month
5 The EXTRACT (FROM data format) Date time division, or a calculation given two dates spaced

Examples : Verify ADD_MONTHS () function

  • Use ADD_MONTHS () function is the main function of adding new date obtained after several months on a specified date.
SELECT SYSDATE,
    ADD_MONTHS(SYSDATE,3) 三个月之后的日期,
    ADD_MONTHS(SYSDATE,-3) 三个月之前的日期,
    ADD_MONTHS(SYSDATE,60) 六十个月之后的日期,
FROM dual;

Examples : all employees required to display the date three months after being hired

SELECT empno,ename,job,sal,hiredate,ADD_MONTHS(hiredate,3)
FROM emp; 

Examples : Verify NEXT_DAY () function

  • The main is to obtain a specified number of date, if the current date 'August 2019 Friday 30th', so if we want to know where the next 'Monday' or 'Sunday' specific date, you can use NEXT_DAY () function.
SELECT 
    SYSDATE,
    NEXT_DAY(SYSDATE,'星期日') 下一个星期日,
    NEXT_DAY(SYSDATE,'星期一') 下一个星期一
FROM dual;

Examples : LAST_DAY () function to verify, seeking the last day of the month

SELECT SYSDATE,
    LAST_DAY(SYSDATE)
FROM dual;

Examples : Query all the information in the full month of employment where their employment is the reciprocal of the third day's hire

  • Every employee has their hire date, so now you want to check out, you hire date falls on the third day month countdown to hire people, you first need to know is where every employee hired last day of the month.
SELECT empno,ename,job,hiredate,LAST_DAY(hiredate) 
FROM emp
WHERE LAST_DAY(hiredate)-2=hiredate;

Examples : MONTHS_BETWEEN () validation function: check out each employee's number, name, date of commission employees, hired a few months and years

  • MONTHS_BETWEEN () function is the function to obtain two month interval date and time
SELECT 
    empno 雇员编号, ename 雇员姓名, hiredate 雇佣日期,
    TRUNC(MONTHS_BETWEEN(SYSDATE,hiredate)) 雇佣总月数,
    TRUNC(MONTHS_BETWEEN(SYSDATE,hiredate)/12) 雇佣总年数
FROM emp;

Examples : check out each employee's number, name, date of employment for several years, has been hired, the number of months, days

  • For this procedure, it must be calculated step, but with some difficulty, since the accuracy is to be operated.
  • For example, today's date is 2019-09-01 day, while BLAKE employment date is 1981-05-01, so the employee was hired to date 38 years, 4 months, 0 days.
  • Step one: find the year in just rely months can be calculated.
SELECT 
    empno 雇员编号, ename 雇员姓名, hiredate 雇佣日期,
    TRUNC(MONTHS_BETWEEN(SYSDATE,hiredate)/12) 雇佣总年数
FROM emp;
  • Step two: Find months, there is a decimal calculation of time, then there is a month of data, requires only mode can be obtained.
SELECT 
    empno 雇员编号, ename 雇员姓名, hiredate 雇佣日期,
    TRUNC(MONTHS_BETWEEN(SYSDATE,hiredate)/12) 已雇佣年数,
    TRUNC(MOD(MONTHS_BETWEEN(SYSDATE,hiredate),12)) 已雇佣月数
FROM emp;
  • Step three: is calculated for the days, because now calculate the year and month, so the day should dig digital information last year and the month. So now the question is, if it is to calculate the number of days the only known formula is "Date 1 - The date 2", then a date certain are using the SYSDATE, and date 2 (should remove the years and months), you can use ADD_MONTHS () function implement this feature.
SELECT 
    empno 雇员编号, ename 雇员姓名, hiredate 雇佣日期,
    TRUNC(MONTHS_BETWEEN(SYSDATE,hiredate)/12) 已雇佣年数,
    TRUNC(MOD(MONTHS_BETWEEN(SYSDATE,hiredate),12)) 已雇佣月数,
    TRUNC(SYSDATE - ADD_MONTHS(hiredate,MONTHS_BETWEEN(SYSDATE,hiredate))) 已雇佣天数
FROM emp;

Examples : EXTRACT () function

  • After a Oracle 9i adds the EXTRACT () function is the main function, this function can be from a date and time (DATE) or time interval (the INTERVAL) taken out in a specific section, this function uses the following syntax:
EXTRACT
    ([YEAR | MONTH | DAY | HOUR | MINUTE | SECOND]
    | [TIMEZONE_HOUR | TIMEZONE_MINUTE]
    | [TIMEZONE_REGION | TIMEZONE_ABBR]
FROM 
     [日期(date_value) | 时间间隔(interval_value)]);

Examples : Remove the year, month, date and time of day data from among the

SELECT 
    EXTRACT(YEAR FROM DATE '2001-09-19') years,
    EXTRACT(MONTH FROM DATE '2001-09-19') months,
    EXTRACT(DAY FROM DATE '2001-09-19') days
FROM dual;
  • It is a date of completion by a string, you can also take advantage of the current date completed. SYSDATE, SYSTIMESTAMP (time stamp).
SELECT SYSDATE,SYSTIMESTAMP
FROM dual;

Examples : Remove the year, month, day, time stamp from among the hours, minutes, seconds

SELECT
    EXTRACT(YEAR FROM SYSTIMESTAMP) years,
    EXTRACT(MONTH FROM SYSTIMESTAMP) months,
    EXTRACT(DAY FROM SYSTIMESTAMP) days,
    EXTRACT(HOUR FROM SYSTIMESTAMP) hours,
    EXTRACT(MINUTE FROM SYSTIMESTAMP) minutes,
    EXTRACT(SECOND FROM SYSTIMESTAMP) seconds
FROM dual;
  • In addition to the above functions, the main function is the acquisition time interval, but here need to use a conversion function: TO_TIMESTAMP (), the string may be changed to the time stamp, but this time the need to use part of the contents of the sub-queries, so here only to make a presentation.

Examples : Get interval between two dates

SELECT 
    EXTRACT(DAY FROM TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss')
        - TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss')) days
FROM dual;

Examples : get two days between the date and time, hours, minutes, seconds

SELECT 
    EXTRACT(DAY FROM datetime_one - datetime_two) days,
    EXTRACT(HOUR FROM datetime_one - datetime_two) hours,
    EXTRACT(MINUTE FROM datetime_one - datetime_two) minutes,
    EXTRACT(SECOND FROM datetime_one - datetime_two) seconds
FROM (
    SELECT TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss') datetime_one,
        TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss') datetime_two
    FROM dual);
  • If you feel too much trouble, you can not use sub-queries, write code according to the original method on the following:
SELECT 
    EXTRACT(DAY FROM TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss')
        - TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss')) days,
    EXTRACT(HOUR FROM TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss')
        - TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss')) hours,
    EXTRACT(MINUTE FROM TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss')
        - TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss')) minutes,
    EXTRACT(SECOND FROM TO_TIMESTAMP('1982-08-13 12:17:57','yyyy-mm-dd hh24:mi:ss')
        - TO_TIMESTAMP('1981-09-27 09:08:33','yyyy-mm-dd hh24:mi:ss')) seconds
FROM dual;
  • So, one way second way is the worst, and not recommended.

6.5 Conversion Functions

  • The main data types used in the database: character, numeric, date (time stamp), then we need to implement conversion operation between these three types of data, which belongs to the function of the transfer function.
No. Function name description
1 TO_CHAR (date | digital | columns, format conversion) The specified data in the specified format string becomes
2 TO_DATE (string | columns, format conversion) The specified string in the format specified type becomes DATE
3 TO_NUMBER (string | column) The specified data type to digital type

6.5.1 TO_CHAR () function

  • In the case of default, if the query is a date, the date the default display format is "31-1-December", and such a date display is certainly not as common "2012-01-31" people look habit, at this time, it can () function of the data displayed formatted date (after the data string formatted) by the TO_CHAR, but if such a format to be completed, the first surrogate markers familiar date formatted .

Date formatting tags:

No. Format Conversion description
1 YYYY Full year figures, said there were four, so the use of four Y
2 Y,YYY In commas
3 YYY After three years of
4 YY After two years of
5 Y Last year
6 YEAR Year textual representation, direct representation of four years
7 MONTH January textual representation, direct representation of two months
8 MM With two digits to represent the month, month two, two M
9 DAY Text represents the number of days
10 DDD The number represents the year (001 to 366) days
11 DD For January in the number (01 to 31) days
12 D It represents the number of the week (1 to 7) days
13 DY It represents the day of the week in words
14 WW It represents the number of weeks of the year
15 W Expressed in number of weeks in January
16 HH Represents a 12-hour, two hours is a digital, two H
17 HH24 It represents the 24-hour clock
18 MY For minutes
19 SS Represents a second, two-digit seconds, two S
20 SSSSS It represents a second number after midnight (0 to 86399)
21 AM|PM (A.M | P.M) For am or pm
22 FM After removing the leading 0 queries, the tag template for extension of time
  • In the TO_CHAR () function which requires two parameters: the date data, format conversion

Examples : Format Date Time

SELECT SYSDATE 当前系统时间,
    TO_CHAR(SYSDATE,'YYYY-MM-DD') 格式化日期,
    TO_CHAR(SYSDATE,'YYYY-MM-DD HH24:MI:SS') 格式化日期时间,
    TO_CHAR(SYSDATE,'FMYYYY-MM-DD HH24:MI:SS') 去掉前导0的时间
FROM dual;
  • Note: Be sure not to cancel the leading 0 in development

Examples : Use a different way to format year, month, day

  • In addition to using markers (a habit, java.text.SimpleDateFormat), you can also use the word representation
SELECT SYSDATE 当前系统时间,
    TO_CHAR(SYSDATE,'YEAR-MONTH-DAY') 格式化日期
FROM dual;

或者:

SELECT SYSDATE 当前系统时间,
    TO_CHAR(SYSDATE,'YEAR-MONTH-DY') 格式化日期
FROM dual;

Examples : check out all the employee information in February each year of employment

SELECT * 
FROM emp 
WHERE TO_CHAR(hiredate,'MM') = 2;

或者:

SELECT * 
FROM emp 
WHERE TO_CHAR(hiredate,'MM') = '02';

范例:将每个雇员的雇佣日期进行格式化显示,要求所有的雇佣日期可以按照“年-月-日”的形式显示,也可将雇佣的年、月、日拆开分别显示

SELECT empno,ename,job,hiredate,
    TO_CHAR(hiredate,'YYYY-MM-DD') 格式化雇佣日期,
    TO_CHAR(hiredate,'YYYY') 年,
    TO_CHAR(hiredate,'MM') 月,
    TO_CHAR(hiredate,'DD') 日
FROM emp;
  • TO_CHAR() 函数的最为重要的功能是可以将数字格式化,例如:2389042809,如果是有经验的财务人员会按照三位一分:2,389,042,809 ,而要想按照此方法处理数字,就必须格式化。

数字格式化标记

No. 转换格式 描述
1 9 表示一位数字
2 0 表示前导0
3 $ 将货币的符号信息显示为美元符号
4 L 根据语言环境不同,自动选择货币符号
5 . 显示小数点
6 , 显示千位符

范例:格式化数字显示

SELECT
    TO_CHAR(987654321.789,'999,999,999,999.9999') 格式化数字,
    TO_CHAR(987654321.789,'000,000,000,000.0000') 格式化数字
FROM dual;
  • 除了直接对数字格式化,也可以进行货币的显示
SELECT
    TO_CHAR(987654321.789,'L999,999,999,999.9999') 显示货币,
    TO_CHAR(987654321.789,'$999,999,999,999.9999') 显示美元
FROM dual;
  • 在开发之中,TO_CHAR() 函数的作用还是非常明显的!建议掌握!

6.5.2 TO_DATE() 函数

  • 这个函数主要是将字符串变为日期型数据,而改变的过程里面依然需要之前 TO_CHAR() 函数出现的相关标记。

范例:转换时间显示

SELECT 
    TO_DATE('1979-09-19','YYYY-MM-DD')
FROM dual;
  • 在之前讲解日期函数时使用了一个 TO_TIMESTAMP() 函数,这个函数是将字符串变为时间戳。

范例:时间戳转换

SELECT
    TO_TIMESTAMP('1981-09-27 18:07:10','YYYY-MM-DD HH24:MI:SS') datetime
FROM dual;

6.5.3 TO_NUMBER() 函数

  • 作用是将字符串变为数字

范例:将字符串变为数字

SELECT
    TO_NUMBER('09') + TO_NUMBER('19') 加法操作,
    TO_NUMBER('09') * TO_NUMBER('19') 乘法操作
FROM dual;
  • 但是在之前强调过,Oracle 里面支持数据类型的自动转型操作,上面的代码也可写为
SELECT '09' + '19' 加法操作,
    '09' * '19' 乘法操作
FROM dual;

6.6、通用函数

  • 这些函数是 Oracle 数据库的特色,对于这些函数了解有一定的好处。
No. 函数名称 描述
1 NVL(数字|列 , 默认值) 如果显示的数字是null的话,则使用默认数值表示
2 NVL2(数字|列,返回结果一(不为空显示),返回结果二(为空显示)) 判断指定的列是否是null,如果不为null则返回结果一,为空则返回结果二
3 NULLIF(表达式一,表达式二) 比较表达式一和表达式二的结果是否相等,如果相等返回NULL,如果不相等返回表达式一
4 DECODE(列|值,判断值1,显示结果1,判断值2,显示结果2,...,默认值) 多值判断,如果某一个列(或一个值)与判断值相同,则使用指定的显示结果输出,如果没有满足条件,在显示默认值
5 CASE 列|数值 WHEN 表达式1 THEN 显示结果1 ... ELSE 表达式N ... END 用于实现多条件判断,在WHEN之后编写条件,而在THEN之后编写条件满足的显示操作,如果都不满足则使用ELSE 中的表达式处理
6 COALESCE(表达式1,表达式2,...表达式n) 将表达式逐个判断,如果表达式1的内容是null,则显示表达式2,如果表达式2的内容是null,则显示表达式3,依次类推,如果表达式n的结果还是null,则返回null
  • 对于通用函数而言,只有两个核心函数:NVL() , DECODE()

6.6.1 使用 NVL() 函数处理 null

  • 在数据库之中,null 是无法进行计算的,即,在一个数学计算之中如果存在了 null,则最后的结果也肯定是 null

范例:查询出每个雇员的编号、姓名、职位、雇佣日期、年薪

  • 对于年薪最准确的做法是应该计算 “sal + comm”,可是这个时候 comm 列上是存在了 null 数据的
SELECT empno,ename,job,hiredate,(sal+comm)*12 年薪,sal,comm
FROM emp;
  • 因为 comm 上的内容有的是 null,而现在发现,只要是 comm 为 null 的计算,最终的结果就是 null ,所以在这种情况下需要针对于 null 进行处理,肯定将 null 变为0才合适

范例:验证 NVL()

SELECT NVL(null,0),NVL(3,0) 
FROM dual;
  • 这个时候发现如果为 null,那么就将其变为了0,如果不是 null,就继续使用指定的数值
SELECT empno,ename,job,hiredate,(sal+NVL(comm,0))*12 年薪,sal,comm
FROM emp;

6.6.2 NVL2() 函数

  • NVL2() 函数是在 Oracle 9i 之后增加的一个新的功能函数,相比较 NVL() 函数,NVL2() 函数可以同时对为 null 或不为 null 进行分别判断并返回不同的结果

范例:查询每个雇员的编号、姓名、年薪(sal + comm)、基本工资、奖金

SELECT empno,ename,job,hiredate,NVL2(comm,sal+comm,sal),sal,comm
FROM emp;

6.6.3 NULLIF() 函数

  • NULLIF(表达式一,表达式二) 函数的主要功能是判断两个表达式的结果是否相等,如果相等则返回 NULL ,不相等则返回表达式一

范例:验证 NULLIF() 函数

SELECT NULLIF(1,1),NULLIF(1,2)
FROM dual;

范例:查询雇员编号、姓名、职位,比较姓名和职位的长度

SELECT empno,ename,job,LENGTH(ename),LENGTH(job),NULLIF(LENGTH(ename),LENGTH(job)) nullif
FROM emp;

6.6.4 DECODE() 函数

  • DECODE() 函数是 Oracle 中最有特色的一个函数,DECODE() 函数类似于程序中的 if...else if...else ,但是判断的内容都是一个具体的值,语法如下:

    DECODE(列|表达式, 值1, 输出结果, 值2, 输出结果, ..., 默认值)

范例:测试DECODE() 函数

SELECT 
    DECODE(2,1,'内容为一',2,'内容为二'),
    DECODE(2,1,'内容为一','没有条件满足')
FROM dual;

范例:现在雇员表中的工作有以下几种:CLERK:业务员, SALESMAN:销售人员, MANAGER:经理, ANALYST:分析员, PRESIDENT:总裁 ,要求查询雇员的姓名、职位、基本工资等信息,但是要求将所有的职位信息都替换为中文显示。

SELECT ename,sal,
DECODE(job,
    'CLERK','业务员',
    'SALESMAN','销售人员',
    'MANAGER','经理',
    'ANALYST','分析员',
    'PRESIDENT','总裁') job
FROM emp;
  • 但是需要注意的是,如果使用 DECODE() 函数判断,那么所有的内容都要判断,如果只判断部分内容,其它内容就会显示 null

6.6.5 CASE 表达式

  • CASE 表达式是在 Oracle 9i 引入的,功能与DECODE() 有些类似,都是执行多条件判断。不过严格来讲,CASE表达式本身并不属于一种函数的范畴,它的主要功能是针对于给定的列或者字段进行依次判断,在 WHERE 中编写判断语句,而在 THEN 中编写处理语句,最后如果都不满足则使用 ELSE 进行处理。

范例:显示每个雇员的工资、姓名、职位,同时显示新的工资(新的工资标准:办事员增长10%,销售人员增长20%,经理增长30%,其他职位的人增长50%)

SELECT ename,sal,
    CASE job WHEN 'CLERK' THEN sal * 1.1
        WHEN 'SALESMAN' THEN sal * 1.2
        WHEN 'MANAGER' THEN sal * 1.3
    ELSE sal * 1.5
    END 新工资
FROM emp;

6.6.6 COALESCE() 函数

  • COALESCE(表达式1, 表达式2, 表达式3,...表达式n) 函数的主要功能是对 null 进行操作,采用依次判断表达式的方式完成,如果表达式1为 null,则显示表达式2的内容,如果表达式2的内容为 null,则显示表达式3的内容,依次类推,判断到最后如果还是null,则最终的显示结果就是 null 。

范例:验证 COALESCE() 函数

SELECT ename,sal,comm,COALESCE(comm,100,2000),
    COALESCE(comm,null,null)
FROM emp;
  • 小结:
    • 这些通用函数都具备一些逻辑性的操作在里面,在以后进行程序编写时还是会使用到的。
    • NVL() 和 DECODE() 是通用函数的基础,其他函数都在此函数之上进行功能扩充。

说明:本学习资料是根据李兴华的Oracle开发实战经典整理

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160466.htm