是否可以根据条件来对join
进行条件设置?
例如,如果@DoJoin
为 true ,则执行inner join
。它将替换如下内容:
declare @DoJoin bit = 1
if @DoJoin = 1
BEGIN
select T.* from T inner join L on T.col = L.col
END
ELSE
BEGIN
select T.* from T
END
答案 0 :(得分:2)
如果我了解您的数据如何工作,则可能根本不需要联接,因为您只是将联接用作过滤器。因此,如果是这样,您只需执行一个查询即可。
select T.* from T
where @DoJoin = 0 or exists(SELECT * FROM L where L.col = T.col)
答案 1 :(得分:1)
DECLARE @DoJoin BIT = 1
SELECT
T.*
FROM
T LEFT JOIN L ON T.col = L.col
WHERE
--Optional INNER/LEFT JOIN
(
--LEFT JOIN
@DoJoin = 0
OR
--INNER JOIN
(
-- only return rows from T where they have a record in L
@DoJoin = 1
AND
L.col IS NOT NULL
)
)