You need to pull out the names of the main tables. Select ... From TableName There are four types of queries:
1. Select ... From TableName 2. Select ... From Only TableName 3. Select ... From TableName1 Union Select ... From TableName2 4. Select ..., Exists(SELECT true FROM _tName WHERE ...) From TableName Wrote a regular season: (with gims test parameters here ) (scary queries with multiple line breaks, tabs and spaces, so I inserted \s\t\r\n everywhere)
(?:[\s\t\r\n]*select.+?from[\s\t\r\n]*(?:only|)[\s\t\r\n]*)(\S*) Breaking through on the 4th example, how to take into account subqueries? For example, to select only Select..From between which there is not one more Select . If you just make greedy, then not all tables are found when Union