从sql中获取表名

 <dependency>
        <groupId>com.github.jsqlparser</groupId>
        <artifactId>jsqlparser</artifactId>
        <version>0.9</version>
</dependency>
import java.io.StringReader;
import java.util.List;

import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;


public class DataPermissionSqlUtil {

    
    private static CCJSqlParserManager pm = new CCJSqlParserManager();
    

    
    /**
     *  detect table names from given table 
     *  ATTENTION : WE WILL SKIP SCALAR SUBQUERY IN PROJECTION CLAUSE 
     * */
    private static List<String> getTableNames(String sql) throws Exception {
        List<String> tablenames = null;
        TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
        Statement statement = pm.parse(new StringReader(sql));
        if (statement instanceof Select) {
            tablenames = tablesNamesFinder.getTableList((Select) statement);
        } else if (statement instanceof Update) {
            return null;
        } else if (statement instanceof Delete) {
            return null;
        } else if (statement instanceof Replace) {
            return null;
        } else if (statement instanceof Insert) {
            return null;
        }
        return tablenames;
    }
    public static void main(String[] args) {
        String sql = " select d.* from (SELECT qt.qt_org_id as orgId,qt.qt_owner_id as ownerId,own.OWN_NAME as ownerName, mat.mat_barcode as matBarcode, mat.MAT_CODE as matCode, mat.MAT_NAME as matName, "
                + " m.avgDailyOutboundQty as avgDailyOutboundQty, sum(qt.QT_ONHAND_QTY) availableQty"
                + " from riv_quant qt "
                + " right join (select ONH_OWNER_ID as ownId, chl.CHL_MATERIAL_ID as matId"
                + " from riv_check_l chl "
                + " INNER JOIN riv_outbound_notice_h onh on onh.ONH_ID = chl.CHL_ONH_ID "
                + "  where onh.onh_status = 90  "
                + " GROUP BY chl.CHL_MATERIAL_ID) m on m.matId = qt.QT_MATERIAL_ID "
                + " INNER JOIN riv_owner own on own.OWN_ID = qt.QT_OWNER_ID "
                + " inner join riv_material mat on mat.mat_id = qt.QT_MATERIAL_ID "
                + " GROUP BY m.ownId, m.matId) d ";
        try {
            List<String> tablenames = getTableNames(sql);
            System.out.println(tablenames);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
}
[riv_quant, riv_check_l, riv_outbound_notice_h, riv_owner, riv_material]
原文地址:https://www.cnblogs.com/tonggc1668/p/6992902.html