sql嵌套select解析

发布于 2024-12-07 15:11:41 字数 583 浏览 2 评论 0原文

情况: 我有几个 SSRS 报告,需要记录其中的 sql 代码。 为此,我需要一次又一次以完全相同的方式格式化代码。

问题: 在我的一些报告中,我有这样的结构

select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where

,我希望结果是

select outer
from (
    select outin
    from (
        select inner
        from (
            select innerMax
            from
        )z
        where
    )x
    where dateadd(d,12,getdate())
)y
where

,但是我在缩进嵌套选择方面遇到问题,

如果您能为我提供示例,我将非常感激。 我使用过分割、正则表达式、子字符串……

问候

Situation:
I have several SSRS reports of which I need the sql-code to be documented.
For this I need the code to be formatted in exactly the same way time and time again.

Problem:
In some of my reports I have structures like

select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where

And I want the result to be

select outer
from (
    select outin
    from (
        select inner
        from (
            select innerMax
            from
        )z
        where
    )x
    where dateadd(d,12,getdate())
)y
where

But I have problems with indenting the nested select's

I'd really appreciate it if you can provide me with examples.
I've used splits, regex, substrings, ...

greetings

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情栀口红 2024-12-14 15:11:41

这比您想象的要棘手:拆分、子字符串和正则表达式不足以可靠地解决这个问题。考虑 SQL 代码中的注释或字符串文字,它们可能包含看起来像 SQL 的文本或包含括号,这会扰乱您的缩进级别。

更好的方法是使用 SQL 解析器。这是 python-sqlparse: 的演示,

#!/usr/bin/env python
import sqlparse

sql = """
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
"""

print sqlparse.format(sql, reindent=True)

它将打印:

select outer
from
  (select outin
   from
     (select inner
      from
        (select innerMax
         from)z
      where)x
   where dateadd(d,12,getdate()))y
where

This is trickier than you might think: split, substring and regex will not be enough to reliably tackle this problem. Consider comments, or string literals inside your SQL code that might contain text that looks like SQL or contains parenthesis which will mess up your indentation levels.

A better way is to use an SQL parser. Here's a demo with python-sqlparse:

#!/usr/bin/env python
import sqlparse

sql = """
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
"""

print sqlparse.format(sql, reindent=True)

which will print:

select outer
from
  (select outin
   from
     (select inner
      from
        (select innerMax
         from)z
      where)x
   where dateadd(d,12,getdate()))y
where
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文