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
). 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
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. For simple select and insert queries, this could be a good starting point.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.