ORACLE数据库字符串和日期的转换以及对null值的处理

今天项目用到了对日期的格式转换,并且由于日期数据比较杂,存在null值和' ',所以需要对他们处理:

1.字符串转日期 ,to_date(exp1,exp2); exp1表示字符串,exp2便是字符串的格式。例如str='20180124':

 to_date(str,'yyyymmdd');

2.由日期转为字符串则是, to_char(exp1,exp2),exp1表示格式为date的日期,exp2表示要转为字符串的格式,例如由当前系统转为:2018-01-24 17:00:01

 to_char(sysdate,'yyyymmdd hh24:mi:ss');


3.根据以上两种,当把字符串20180101转为字符串2018-01-01;

 to_char(to_date('20180101','yyyymmdd') ,'yyyy-mm-dd'));

4.如果需要处理的数据中既有' '(空格) 又有 null,则可以对空值进行处理。

 4.1 nvl(exp1,exp2); 当exp1位null时,则返回exp2;

 4.2 nvl2(exp1,exp2,exp3);当exp1为null时,返回exp2,否则返回exp3;

扫描二维码关注公众号,回复: 1032560 查看本文章

4.3 decode(exp1,exp2,exp3,exp4);如果exp1和exp2相等,则返回exp3,否则返回exp4;

案例:把字符串日期20180101转为字符串2018-01-01(查询的数据有null和空格),如果查询结果为exp

思路:如果为null,则转为' ' ,再用decode,如果为' ',则返回' ' ,否则转换格式进行返回。

decode(nvl(exp,' '),' ',' ',to_char(to_date(exp,'yyyymmdd') ,'yyyy-mm-dd')));

5.当然也可以使用字符串截取的方式:

decode(nvl(exp,' '),' ',' ',substr(exp,1,4)||'-'||substr(exp,5,2)||'-'||substr(exp,7,2)) ;







猜你喜欢

转载自blog.csdn.net/cydbetter/article/details/79152892