Visit SQL statement recursively

This demo illustrate how to find out all kinds of SQL statements in a script quickly. Find out all SQL statements inside a PLSQL block/package/procedure/function; Find out nested subquery in a select/delete/update statement; Find out querys in a union select statement; Find out sub-queries in where clause, select list and etc.

Code in Java:

        TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvoracle);
        sqlparser.sqlfilename  = args[0];

        int ret = sqlparser.parse();
        if (ret == 0){
            for(int i=0;i<sqlparser.sqlstatements.size();i++){
                iterateStmt(sqlparser.sqlstatements.get(i));
            }
        }else{
            System.out.println(sqlparser.getErrormessage());
        }

    protected static void iterateStmt(TCustomSqlStatement stmt){
        System.out.println(stmt.sqlstatementtype.toString());
        for (int i=0;i<stmt.getStatements().size();i++){
           iterateStmt(stmt.getStatements().get(i));
        }
    }

Download this demo: Java version, C# version

If you need to process all elements of a SQL statement, you may use visitor pattern to iterate all parse tree nodes just like this XML demo does.

Leave a Reply

Your email address will not be published. Required fields are marked *