0

我有这样的参数

declare @Phl1_descr varchar(50)
SET @Phl1_descr = 'Greece'

declare @Phl2_descr varchar(50)
SET @Phl2_descr = 'Coffee & Beverages'

我想用上述参数加入两个表(如果它们不为空),所以我尝试在ONmy 的“”关键字中执行以下操作JOIN

ON 
      (CASE WHEN LEN(@Phl1_descr) > 0 THEN A.Phl1_descr ELSE B.Phl1_descr END) = B.Phl1_descr AND
      (CASE WHEN LEN(@Phl2_descr) > 0 THEN A.Phl2_descr ELSE B.Phl2_descr END) = B.Phl2_descr

但是,如果我发送 as 之类的参数之一'',它就不起作用。有更简单的想法吗?

4

2 回答 2

1

是否可以使用更简单的解决方案?喜欢:

IF @Phl1_descr IS NOT NULL AND @Phl2_descr IS NOT NULL
BEGIN
   SELECT *
   FROM Table1 as A
   LEFT JOIN Table2 as B on A.Phl1_descr=B.Phl1_descr and A.Phl2_descr=B.Phl2_descr
END
ELSE IF @Phl1_descr IS NOT NULL AND @Phl2_descr IS NULL
BEGIN
   SELECT *
   FROM Table1 as A
   LEFT JOIN Table2 as B on A.Phl1_descr=B.Phl1_descr
END
ELSE IF @Phl1_descr IS NULL AND @Phl2_descr IS NOT NULL
BEGIN
   SELECT *
   FROM Table1 as A
   LEFT JOIN Table2 as B on A.Phl2_descr=B.Phl2_descr
END

所以你会得到一个更简单的执行计划和更简单的逻辑。

您还可以使用... CASE WHEN @Phl1_descr IS NULL THEN ...检查 NULL 值

于 2013-07-05T08:54:27.360 回答
0

有趣但

B.Phl1_descr = B.Phl1_descr 

不工作但

ISNULL(B.Phl1_descr,'-1') = ISNULL(B.Phl1_descr,'-1')

作品,

因此,只需对以下代码进行简单更改即可解决

  (CASE WHEN LEN(@Phl1_descr) > 1 THEN A.Phl1_descr ELSE ISNULL(B.Phl1_descr,'-1') END) = ISNULL(B.Phl1_descr,'-1') AND
  (CASE WHEN LEN(@Phl2_descr) > 1 THEN A.Phl2_descr ELSE ISNULL(B.Phl2_descr,'-1') END) = ISNULL(B.Phl2_descr,'-1') AND
于 2013-07-05T10:36:10.117 回答