Python 有没有一种方法可以跨多行编写带有注释的SQL查询?
编写正则表达式时,可以跨多行编写表达式并包含注释,然后在传递编译版本之前使用Python 有没有一种方法可以跨多行编写带有注释的SQL查询?,python,sql,pandas,Python,Sql,Pandas,编写正则表达式时,可以跨多行编写表达式并包含注释,然后在传递编译版本之前使用re.VERBOSE选项编译表达式。我想对熊猫执行类似的操作。请阅读\u sql\u query 例如,而不是: result = pd.read_sql_query('select a.gvkey, a.tic, a.datadate as fyearend, year(a.datadate) as year, month(a.datadate) as fyrc, b.datadate, month(b.datadat
re.VERBOSE
选项编译表达式。我想对熊猫执行类似的操作。请阅读\u sql\u query
例如,而不是:
result = pd.read_sql_query('select a.gvkey, a.tic, a.datadate as fyearend, year(a.datadate) as year, month(a.datadate) as fyrc, b.datadate, month(b.datadate) as month, b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate) where a.TIC = "IBM" and a.datafmt = "STD" and a.consol="C" and a.indfmt = "INDL" and year(a.datadate)>1980', engine)
我想写一些类似于:
q = """select a.gvkey,
a.tic, #COMMENTS
a.datadate as fyearend, #COMMENTS
year(a.datadate) as year, #COMMENTS
month(a.datadate) as fyrc, b.datadate,
month(b.datadate) as month,
b.trt1m
from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate)
where a.TIC = "IBM"
and a.datafmt = "STD"
and a.consol="C"
and a.indfmt = "INDL"
and year(a.datadate)>1980
"""
result = p.read_sql_query(q ,engine)
我的问题是关于在多行中拆分python命令的问题,但我想在查询中添加注释
正如我提到的,我想在pandas/SQL案例中做的事情与正则表达式案例中使用re.VERBOSE
可以做的事情类似。下面是一个使用regex的示例:
pattern = r'''\s(shares?| #COMMENTS
warrants?| #COMMENTS
stock| #AND SO ON...
(non)?vest(ed)?
)\b
'''
crit = re.compile(pattern_nopt, re.VERBOSE)
match=re.search(crit, string)
这将使查询更具可读性,我发现在与合著者共享代码时对查询进行详尽的注释非常重要。是的,它可以工作,但您必须使用正确的注释:
--
用于内联注释/*foo*/代码>(如C中)用于多行注释
所以看起来是这样的:
q = """select a.gvkey,
a.tic, -- COMMENTS
a.datadate as fyearend, -- COMMENTS
year(a.datadate) as year, /* Another very long
and multi-lines comment... */
month(a.datadate) as fyrc, b.datadate,
month(b.datadate) as month,
b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate)
where a.TIC = "IBM"
and a.datafmt = "STD"
and a.consol="C"
and a.indfmt = "INDL"
and year(a.datadate)>1980
"""
result = p.read_sql_query(q, conn)
mgc,谢谢!这在我使用多行注释(/*foo*/
)时有效,但在我使用内联注释(--
)时无效。你有没有想过为什么会这样?@ArthurMorris不客气!我真的不知道,我(成功地)测试了内联分隔符First。您确定以--
开头的注释以行尾结尾吗?或者你有任何错误信息吗?评论似乎以新行结尾,但我可能错了。我得到的错误是:语法错误,应为以下错误之一:;,!,!!,&,(,*,***,+,-,'。,/,=,和,EQ,EQT,EXCEPT,GE,GET,GROUP,GT,GTT,HAVING,INTERSECT,LE,LET,LT,LTT-2147295222错误22-322
再次感谢您的回答!我将自己进一步调试。事实证明,我的问题是由于我正在查询的数据库使用SAS SQL,因此-
注释不能识别为注释s、 我想教训是,SQL查询中的注释格式是由处理查询的系统决定的,而不是由Python决定的。