Skip to content

Examples of SQL building part 2

Tobias edited this page Nov 13, 2019 · 3 revisions

Replacing column names within the where clause of a statement

SELECT col1 AS a, col2 AS b, col3 AS c FROM table WHERE col_1 = 10 AND col_2 = 20 AND col_3 = 30

within this sql in all column names from where the underscore should be removed.

Select stmt = (Select) CCJSqlParserUtil.parse("SELECT col1 AS a, col2 AS b, col3 AS c FROM table WHERE col_1 = 10 AND col_2 = 20 AND col_3 = 30");
System.out.println("before " + stmt.toString());
    
((PlainSelect)stmt.getSelectBody()).getWhere().accept(new ExpressionVisitorAdapter() {
    @Override
    public void visit(Column column) {
        column.setColumnName(column.getColumnName().replace("_", ""));
    }
});
    
System.out.println("after " + stmt.toString());

The interesting part starts with the casting of getSelectBody() to PlainSelect. If there is a more complex sql one should use here as well a visitor. Now the expression from getWhere is traversed using an ExpressionVisitor. ExpressionVisitorAdapter is a full implementation of an ExpressionVisitor. Therefore we only need to override the visit(Column column) method to get access to all Column instances within the where expression. The replacement itself is trivial.