I need a way to search for a word within an SQL query, and to be able to determine whether or not that word is within a subquery or the main query.
For example:
SELECT *
FROM products
WHERE id NOT IN (SELECT product_id
FROM tagmap
WHERE tag_id = 1)
I need to replace the instance of the word WHERE with, say, WHERE 1=1 AND in the query string, but only in the main query, not in the subquery.
This is only an example of the issue I’m facing. The real queries are much bigger than this and contain several subqueries! Also, there are hundreds of queries I need to do this for, so I need to be able to do this automatically.
I think the following regex:
will match any instance of “WHERE”:
ie Won’t detect instances of WHERE that occur inside a
(..).It’s worked on the few test cases I’ve tried… and I’m not going to do any more testing without further clarifcation of your requirements…
EG below, I’ve indicated the matched instances by surrounding with tildes:
~WHERE~.I’d strongly recommend you test this thoroughly before relying on it.
EDIT: A basic .NET implementation… because I’ve got VS open at the moment… 😉
EDIT: To do this in a text editor…
Visual Studio will allow you do perform a search/replace based on a regex. I’d imagine something like Notepad++ would do it (at least with the aid of a plugin). Or this might help you: http://www.regular-expressions.info/editpadpro.html
Otherwise, knock up something that’ll read/modify your text file, eg using PHP, .NET, Java, ….