Skip to content

Examples of SQL analyzing

Tobias edited this page Nov 13, 2019 · 1 revision

Retrieve all selected items of a SQL statement

The task here is to build a map, where the alias is the key and the expression to this alias the value of one Map entry.

Select stmt = (Select) CCJSqlParserUtil.parse("SELECT col1 AS a, col2 AS b, col3 AS c FROM table WHERE col1 = 10 AND col2 = 20 AND col3 = 30");
        
Map<String, Expression> map = new HashMap<>();        
for (SelectItem selectItem : ((PlainSelect)stmt.getSelectBody()).getSelectItems()) {
    selectItem.accept(new SelectItemVisitorAdapter() {
        @Override
        public void visit(SelectExpressionItem item) {
            map.put(item.getAlias().getName(), item.getExpression());
        }
    });
}
    
System.out.println("map " + map);

Selected items of a SQL could be of different type. We are now interested in so called SelectExpressionItems. These are those consisting of an expression optionally named by an alias. So with a SelectItemVisitor we are filtering those items. Directly from our SelectExpressionItem we can get the alias and the expression.

This will then return:

map {a=col1, b=col2, c=col3}
Clone this wiki locally
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy