Get columns in select list
It’s quite simple and straightforward to get column information in select list by using a SQL Parser which maybe hard to achieve when using other tools like regex when query become more complex such as including nested subquery.
Below is a simple Java program that get all columns in select list:
package demos.gettablecolumns; import gudusoft.gsqlparser.TCustomSqlStatement; import gudusoft.gsqlparser.EDbVendor; import gudusoft.gsqlparser.ESqlStatementType; import gudusoft.gsqlparser.TGSqlParser; import gudusoft.gsqlparser.nodes.TResultColumnList; import gudusoft.gsqlparser.stmt.TSelectSqlStatement; import java.io.File; public class getResultColumn { public static void main(String args[]) { TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvoracle); sqlparser.sqltext = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a"; int ret = sqlparser.parse(); if (ret == 0){ TSelectSqlStatement select = (TSelectSqlStatement)sqlparser.sqlstatements.get(0); TResultColumnList columns = select.getResultColumnList(); for(int i = 0; i < columns.size();i++){ System.out.println(columns.getResultColumn(i).toString()); } }else{ System.out.println(sqlparser.getErrormessage()); } } }
The output of is:
a b c DATETOSTRING(date_attr_name,'mm/dd/yyyy')
Download this demo: Java version