简体   繁体   English

与CRUD操作无关,从字符串查询中获取表名

[英]Get table name from string query irrespective of CRUD operation

I have string like below. 我有下面的字符串。 I have to get all table name from this. 我必须从中获取所有表名。

 select SEQ_NO,CODE,CD_NAME,CD_TYPE,CD_CITY,CDS_STATUS,CDS_SUBSTATUS,  
 to_char(CDS_LAST_MOD_DATE,'dd/mm/yyyy') as CDS_LAST_MOD_DATE   from  
 company_details left outer join on company_details_status where  
 cd_seq_no=cds_seq_no,CODE=(select CODE from company_details where cd_seq_no='1' )  order by CDS_LAST_MOD_DATE.


Insert into table1 value(?,?)
Insert into table1 (col1,col2) values(?,?)

How to get table name for insert query like above. 如何为上面的插入查询获取表名。

Here is a short code which hints at how you might approach this problem. 这是一个简短的代码,提示您如何解决此问题。 It uses a regex matcher with the following pattern: 它使用具有以下模式的正则表达式匹配器:

FROM\s+(\S+)|JOIN\s+(\S+)|INSERT\s+INTO\s+(\S+)

The aim here is to capture table names whenever they occur in select statements (after FROM and JOIN ), or in insert statements (after INSERT INTO ). 这里的目的是捕获表名,只要它们出现在select语句(在FROMJOIN )或insert语句(在INSERT INTO )中。 Note that the pattern uses an alternation with three capture groups. 请注意,该模式使用具有三个捕获组的交替方式。

String query =  "SELECT a.col1, b.col2 FROM tableA a INNER JOIN tableB b ";
       query += "ON a.key = b.key; INSERT INTO tableC (col1) VALUES ('hello')";
String pattern = "FROM\\s+(\\S+)|JOIN\\s+(\\S+)|INSERT\\s+INTO\\s+(\\S+)";

Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(query);
while (m.find()) {
    String match = m.group(1) != null ? m.group(1) :
        (m.group(2) != null ? m.group(2) : m.group(3));
    System.out.println(match);
}

tableA
tableB
tableC

Demo 演示版

Obviously there are many edge cases I may have missed. 显然,我可能错过了许多边缘案例。 In general, for a complete solution you might have to write an actual SQL parser. 通常,对于完整的解决方案,您可能必须编写实际的SQL解析器。 For simple select and insert queries, this could be a good starting point. 对于简单的选择和插入查询,这可能是一个很好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM