在WHERE子句中转换多个“旧格式”连接

时间:2015-09-18 05:31:51

标签: sql-server tsql join database-migration

我在SQL Server中有以下代码结构。它在WHERE子句中使用多个旧格式* =连接?

$(PRODUCT_NAME)

在实际代码中,选择是动态生成的sql的混搭的母亲。但实际上,STRUCTURE就像我上面所示。

上面模板的STRUCTURE应该是什么,以便它使用正确的LEFT OUTER JOIN语法,而不改变查询的逻辑?

这样的事可能会起作用吗?

SELECT ....
FROM (select ...) L1,
     (select ...) L2,
     (select ...) SE,
     (select ...) EX,
     (select ...) SE,
     (select ...) Y1,
     (select ...) Y2,
     (select ...) Y3,
     (select ...) Y4,
     (select ...) Y5
WHERE SE.FV = EX.FV
    and SE.FV *= Y1.FV
    and SE.FV *= Y2.FV
    and SE.FV *= Y3.FV
    and SE.FV *= Y4.FV
    and SE.FV *= Y5.FV
    and SE.L1 *= L1.FV
    and SE.L2 *= L2.FV
GROUP BY L1.FV, L1.Descr, L2.FV, L2.Descr
ORDER BY L1.FV, L1.Descr, L2.FV, L2.Descr

2 个答案:

答案 0 :(得分:2)

我希望,您的查询可以转到以下结构。

SELECT      L1.FV, 
            L1.Descr, 
            L2.FV, 
            L2.Descr,
            .. 
FROM                (select ...) L1
JOIN/LEFT JOIN      (select ...) L2 ON L2.Col = ....
JOIN/LEFT JOIN      (select ...) SE ON SE.Col = ....
JOIN/LEFT JOIN      (select ...) EX ON EX.Col = ....
JOIN/LEFT JOIN      (select ...) SE ON SE.Col = ....
JOIN/LEFT JOIN      (select ...) Y1 ON Y1.Col = ....
JOIN/LEFT JOIN      (select ...) Y2 ON Y2.Col = ....
JOIN/LEFT JOIN      (select ...) Y3 ON Y3.Col = ....
JOIN/LEFT JOIN      (select ...) Y4 ON Y4.Col = ....
JOIN/LEFT JOIN      (select ...) Y5 ON Y5.Col = ....
GROUP BY L1.FV, L1.Descr, L2.FV, L2.Descr
ORDER BY L1.FV, L1.Descr, L2.FV, L2.Descr;

答案 1 :(得分:1)

您可能希望通过使用这样的CTE将“动态生成的sql的混搭”与STRUCTURE分开:

WITH 
    SE AS (select 1 AS X, 2 AS FV, 3 AS L1, 4 AS L2),
    EX AS (select 1 AS X, 2 AS FV),
    Y1 AS (select 1 AS X, 2 AS FV),
    Y2 AS (select 1 AS X, 2 AS FV),
    Y3 AS (select 1 AS X, 2 AS FV),
    Y4 AS (select 1 AS X, 2 AS FV),
    Y5 AS (select 1 AS X, 2 AS FV),
    L1 AS (select 1 AS X, 3 AS FV, 'y' AS Descr),
    L2 AS (select 1 AS X, 4 AS FV, 'z' AS Descr)
SELECT L1.FV, L1.Descr, L2.FV, L2.Descr
FROM 
     SE
     INNER JOIN EX ON EX.FV = SE.FV
     LEFT JOIN Y1 ON Y1.FV = SE.FV
     LEFT JOIN Y2 ON Y2.FV = SE.FV
     LEFT JOIN Y3 ON Y3.FV = SE.FV
     LEFT JOIN Y4 ON Y4.FV = SE.FV
     LEFT JOIN Y5 ON Y5.FV = SE.FV
     LEFT JOIN L1 ON L1.FV = SE.L1
     LEFT JOIN L2 ON L2.FV = SE.L2
GROUP BY L1.FV, L1.Descr, L2.FV, L2.Descr
ORDER BY L1.FV, L1.Descr, L2.FV, L2.Descr