日期:2014-05-18  浏览次数:20417 次

SQL语句的where子句怎么找出来
我想找出sql中的主(即不是嵌套那个)select中的where子句,请问那位大神知道用程序或正则表达式找出来呀,比如:
select * from payment,employee where(((1=1 and (exists(select name from employee E where E.name = payment.name)) and ((payment.name) in (select name from employee where (department='Art Designing' and employee.name=payment.name))) and (payment.name = 'jack'))) and ((1=1 and (employee.sex = 'F'))) and ((payment.name=employee.name))) order by ...
虽然上面的sql比较长,但这句sql是找出第一个where至order by的内容即最大的括号里的内容,大家有什么方法呢,供小弟参考^_^


------解决方案--------------------
实现我就不帮你实现了,我觉得还是复杂的,你在联机丛书当中搜索where子句的语法,语法都是标准的格式的,把语法转换成正则表达式应该是没有问题的,再用正则表达式去匹配
------解决方案--------------------
用python-regex
Python code
#!/usr/bin/python
# encoding: utf-8

import re

sqlscript = '''select * from payment,employee where (((1=1 and (exists(select name from employee E where E.name = payment.name)) and ((payment.name) in (select name from employee where (department='Art Designing' and employee.name=payment.name))) and (payment.name = 'jack'))) and ((1=1 and (employee.sex = 'F'))) and ((payment.name=employee.name))) order by ...
'''

patt = re.compile(r'''select(?P<fieldlist>.*?)\sfrom(?P<tblist>.*?)\swhere\s(?P<conditions>.*)order\sby(?P<orderby>.*)''', re.I|re.U|re.X|re.M)


m = patt.match(' '.join(sqlscript.splitlines()))
print m.groupdict()['conditions']

------解决方案--------------------
你相当于在帮助数据库进行执行计划的分析了,还没学到那一步,MARK下看大大解释
------解决方案--------------------
我看了一下你的where后面有括号,你可以用左右括号对等来判断,当然要排除到字符串中的括号。
------解决方案--------------------
探讨

引用:

我看了一下你的where后面有括号,你可以用左右括号对等来判断,当然要排除到字符串中的括号。

多谢提醒了
你不要看我的where有没有括号,我想问where子句的嵌套子查询是不是都必须要加括号的

------解决方案--------------------
我对Java不了解,解释一下python的正则:
patt = re.compile(r'''
select(?P<fieldlist>.*?)\s # 非贪婪匹配select段落,到" from"为止
from(?P<tblist>.*?)\s # 非贪婪匹配from段落,到" where "为止
where\s(?P<conditions>.*) # 贪婪匹配where段落,
(group\sby(?P<orderby>.*))? # "group by" 段落,可不存在
(order\sby(?P<orderby>.*))? # "order by" 段落,可不存在
''', re.I|re.U|re.X|re.M)