0

当我有多个连接并且传递给它们的变量为空时,我遇到了问题。我想知道当值为空时如何忽略联接。我以为我可以这样做,但是当任何一个参数有值而其他参数没有值时,这不会给我带来正确的结果。

@param1 int = NULL
,@param2 int = NULL
,@param3 int = NULL

SELECT t.ID,t.Col1 FROM Table t
 JOIN RelationalTable1 t1 ON (@param1 IS NULL) OR ( t1.ID1 = t.ID AND t1.ID2 = @param1 )
 JOIN RelationalTable2 t2 ON (@param2 IS NULL) OR ( t2.ID1 = t.ID AND t2.ID2 = @param2 )
 JOIN RelationalTable3 t3 ON (@param3 IS NULL) OR ( t3.ID1 = t.ID AND t3.ID2 = @param3 )

当它们的参数为空时,如何使这些连接消失?

4

1 回答 1

2

看起来您正在使用连接作为过滤器,并且您希望在参数为NULL.

我的建议是切换到left outer join

SELECT t.ID, t.Col1
FROM Table t LEFT JOIN
     RelationalTable1 t1
     ON (@param1 IS NULL) OR ( t1.ID1 = t.ID AND t1.ID2 = @param1 ) LEFT JOIN
     RelationalTable2 t2
     ON (@param2 IS NULL) OR ( t2.ID1 = t.ID AND t2.ID2 = @param2 ) LEFT JOIN
     RelationalTable3 t3
     ON (@param3 IS NULL) OR ( t3.ID1 = t.ID AND t3.ID2 = @param3 )
WHERE ((@param1 IS NULL) or (t1.ID is not null)) and
      ((@param2 IS NULL) or (t2.ID is not null)) and
      ((@param3 IS NULL) or (t3.ID is not null));

where子句说“参数为空或相应表中有匹配项”。

我不确定子句IS NULL中是否需要该参数。on它将为附加表中的每一行生成额外的多行。

于 2013-08-21T14:52:47.017 回答