开发者

sql nested select parsing

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
    )开发者_StackOverflow社区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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜