Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to find all table names in a query

Tags:

.net

regex

sql

I am not that hot at regular expressions and it has made my little mind melt some what.

I am trying to find all the tables names in a query. So say I have the query:

SELECT one, two, three FROM table1, table2 WHERE X=Y

I would like to pull out "table1, table2" or "table1" and "table2"

But what if there is no where statement. It could be the end of the file, or there could be a group by or an order by etc. I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.

Is this a doable Regex expression? Am I being a Regex pleb?

(P.S. this will be done in C# but presume that doesn't matter much).

like image 295
Jon Avatar asked Nov 11 '08 14:11

Jon


People also ask

How show all table names in SQL query?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.

How can I see all table names in mysql?

Then connect to the server using the mysql -u root -p command. Enter the password and execute the SHOW TABLES; command we have discussed above. mysql -u root -p command. Enter the password and execute the SHOW TABLES; command we have discussed above.

Can you use RegEx in SQL query?

You can use RegEx in many languages like PHP, Python, and also SQL. RegEx lets you match patterns by character class (like all letters, or just vowels, or all digits), between alternatives, and other really flexible options.


2 Answers

I found this site that has a GREAT parser!

http://www.sqlparser.com/

well worth it. Works a treat.

like image 165
Jon Avatar answered Sep 28 '22 00:09

Jon


One workaround is to implement a naming convention on tables and views. Then the SQL statement can be parsed on the naming prefix.

For example:

SELECT tbltable1.one, tbltable1.two, tbltable2.three
FROM tbltable1
    INNER JOIN  tbltable2
        ON tbltable1.one = tbltable2.three

Split whitespace to array:

("SELECT","tbltable1.one,","tbltable1.two,","tbltable2.three","FROM","tbltable1","INNER","JOIN","tbltable2","ON","tbltable1.one","=","tbltable2.three")

Get left of elements to period:

("SELECT","tbltable1","tbltable1","tbltable2","FROM","tbltable1","INNER","JOIN","tbltable2","ON","tbltable1","=","tbltable2")

Remove elements with symbols:

("SELECT","tbltable1","tbltable1","tbltable2","FROM","tbltable1","INNER","JOIN","tbltable2","ON","tbltable1","tbltable2")

Reduce to unique values:

("SELECT","tbltable1","tbltable2","FROM","INNER","JOIN","ON")

Filter on Left 3 characters = "tbl"

("tbltable1","tbltable2")

like image 38
Will Avatar answered Sep 27 '22 22:09

Will