Rewrite/Reformat 以调试友好的方式进行多个嵌套子查询

Rewrite/Reformat Multiple Nested Sub Queries in a Debug Friendly manner

是否有更好的方法来重写多个嵌套子查询,使其更易于理解和调试,同时又不影响性能?

(注意:在我的例子中,我得到了一堆相当复杂的子查询,其中许多具有多个连接、where 子句和一些 got case 语句等。将所有内容写成一大块代码是调试的噩梦)

例如:我想重写这个:

SELECT DoSomething(x) AS x
FROM (SELECT DoSomething(x) AS x
      FROM (SELECT DoSomething(x) AS x
            FROM (SELECT DoSomething(x) AS x
                  FROM (SELECT DoSomething(x) AS x
                        FROM (SELECT x
                              FROM tbl_1) AS Q1) AS Q2) AS Q3) AS Q4) AS Q5

变成这样:

--Q1
SELECT *
INTO #Q1
FROM (SELECT x
      FROM tbl_1) AS Q1

--Q2
SELECT *
INTO #Q2
FROM (SELECT DoSomething(x)
      FROM Q1) AS Q2

--Q3
SELECT *
INTO #Q3
FROM (SELECT DoSomething(x)
      FROM Q2) AS Q3

--Q4
SELECT *
INTO #Q4
FROM (SELECT DoSomething(x)
      FROM Q3) AS Q3

--Q5
SELECT *
INTO #Q5
FROM (SELECT DoSomething(x)
      FROM Q4) AS Q4

--Do Something with Q5 then cleanup

DROP TABLE #Q1
DROP TABLE #Q2
DROP TABLE #Q3
DROP TABLE #Q4
DROP TABLE #Q5

上面的示例虽然更多的代码将(希望)允许调试器更容易地 view/select 单个子查询并帮助 him/her 缩小潜在问题的范围

您可能想看看 CTEs

你可以这样写你的例子:

WITH
Q1
AS
(
SELECT x
       FROM tbl_1
),
Q2
AS
SELECT DoSomething(x)
       FROM Q1
),
Q3
AS
(
SELECT DoSomething(x)
       FROM Q2
),
Q4
AS
(
SELECT DoSomething(x)
       FROM Q3
),
Q5
AS
(
SELECT DoSomething(x)
       FROM Q4
)
SELECT *
       FROM Q5;