转换函数、通用函数

1 转换函数

如图所示,数字类型与日期类型之间不可互相转换

1.1 隐式数据类型转换:后台转换

select employee_id,first_name,last_name,salary from emp where employee_id=110;
select employee_id,first_name,last_name,salary from emp where employee_id='110';

1.2 显式数据类型转换:函数转换

1.3 to_char()转换为字符

1.3.1 日期转换为字符

select sysdate,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;
select sysdate,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss AM') from dual;

1.3.2 数字转换为字符

select salary,to_char(salary,'$99,999.0') from emp where rownum<=10;
select salary,to_char(salary,'$99G999D0') from emp where rownum<=10;

【补充说明】:

  D代表:.

  G代表:,

  D、G只能成对出现,不能单独使用

1.4 to_number()字符转换为数字

select to_number('$236','$999') from dual;
select to_number('$123,456.0','$999,999.0') from dual;

1.5 to_date()字符转换为日期

select last_name,hire_date from emp where hire_date>=to_date('2006-01-01','yyyy-mm-dd');
select last_name,hire_date,to_char(hire_date,'yyyy-mm-dd') from emp where hire_date>=to_date('2006-01-01','yyyy-mm-dd');

 

2 通用函数

2.1 NVL函数

nvl(参数1,参数2)

如果参数1为空null,则返回参数2的值(参数1和参数2的数据类型必须匹配

select ename,sal,comm,nvl(comm,0) from emp;
select ename,sal,comm,nvl(to_char(comm),'No Comm') from emp;

2.2 NVL2函数

nvl2(参数1,参数2,参数3)

如果参数1非空not null,则返回参数2的值,否则返回参数3的值(参数1、2、3的数据类型必须匹配)

select employee_id,manager_id,nvl2(manager_id,manager_id,employee_id) from emp;

2.3 nullif

nullif(参数1,参数2)

比较两个参数是否相同,若相同,返回空值null,若不相同,返回参数1

select nullif(1,1) from dual;
select nullif(1,2) from dual;
select first_name,length(first_name) L1,last_name,length(last_name) L2,nullif(length(first_name),length(last_name)) from emp;

posted @ 2021-04-19 16:27  chchcharlie、  阅读(105)  评论(0编辑  收藏  举报