Question

I have parameters like these

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

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

I want to join two tables with the above parameters (if they are not null), so I tried to do something like below in the "ON" keyword of my 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

However if I send one of the parameters like as '', it doesn't work. Any simpler idea?

Was it helpful?

Solution 2

Interesting but

B.Phl1_descr = B.Phl1_descr 

not working but

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

works,

So just a simple change in the below code work it out

  (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

OTHER TIPS

Is it posible to use simpler solution? Like:

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

So you will get a simpler execution plans and simpler logic.

You can also use ... CASE WHEN @Phl1_descr IS NULL THEN ... to check NULL values

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top