问题描述
Hive数据库对数据格式及具体的内容并不关心,只有在数据被读出时才会与定义的Schema进行转换。那这个时候就会出现数据类型转换的问题
准备测试表和数据
create table test_null (id int, age string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
1,23
2,24c
3,32d
4,30
5,NULL
将测试数据加载到test_cast表中,查看表中的数据
![](https://img.haomeiwen.com/i9190482/1d85e4cf3b67072a.png)
表结构为id和age两个字段均为int类型,在Load的示例数据中age列有非数值类型的数据,查看表数据时会看到如上截图类型转换失败显示为NULL。
解决方案
Hive本身没有机制来校验数据的有效性,如果我们想检索出表中类型转换异常的数据,则可以通过nvl和cast两个函数来结合判断数据是否转换失败了。
select id,nvl(cast(age as int), "error") age from test_cast;
将类型异常的数据插入到新的表中,SQL如下:
create table test_exception as
select * from (select id,nvl(cast(age as int), 'error') age from test_cast) as b where b.age='error';
同样也可以只是用cast来进行查找,SQL如下:
create table test_exception as
select * from (select id,nvl(cast(age as int), age) age from test_cast) as b where b.age is null;
网友评论