项目场景:

数据汇聚工具,需要将从不同数据源汇聚来的数据进行治理,治理脚本使用union all联合查询各个不同的数据表。治理后的数据需要插入到目标库,需要根据治理sql语句和目标库中的字段做映射关系。如select "" as name from ****,其中的name需要和目标库表的name字段做映射。


问题描述

sql解析使用如下代码,解析带有union all的sql语句时,报错:java.lang.ClassCastException: net.sf.jsqlparser.statement.select.SetOperationList cannot be cast to net.sf.jsqlparser.statement.select.PlainSelect。

CCJSqlParserManager pm = new CCJSqlParserManager();
Statement statement = pm.parse(new StringReader(sql));
if (statement instanceof Select) {
    Select selectStatement = (Select) statement;
    PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody();
    List<SelectItem> selectItemlist = selectBody.getSelectItems();
    //****************
}   

原因分析:

union all时候,联合的sql需要一个虚拟表,不然会出现报错

解决方案:

解决方案1

sql语句截取,union all多个和单个,解析结果是一致的:

如:select a.name as xingming from tablea a union all select b.name as xingming from tableb b

对这个sql语句截取为简单sql,将union all后面的sql语句截取掉,这样解析出的结果和截取之前是一致的,截取后的sql为:select a.name as xingming from tablea a

解决方案2

在sql外面嵌套一个select 语句,将union all查询的结果作为一个虚拟表,如:

select a.name as xingming from tablea a union all select b.name as xingming from tableb b修改为:select name from (select a.name as xingming from tablea a union all select b.name as xingming from tableb b) t

Logo

一站式 AI 云服务平台

更多推荐