GLP
GLP

Reputation: 3675

How to combine case statement with left join in sql server?

I have two tables that I will have to left join them conditionally. The definition of the tables are tbl1 (col1, col2, col3, …, coln), tbl2 (col1, col2, col3), col1 from both tables is defined as char(2), col2 is defined as char(4). For example tbl1:

col1    col2    col3    …    coln
01      0010
02      0014
10      1235
29      2566
38      1235
8A      1232

tbl2: (x means it is one letter and could be anything from 0-9 or a-z)

col1    col2    col3
0x       NULL
1x       NULL
2x       NULL
...
9x       NULL
13       1234
31       1890
32       1342
3a       1232
...

I need join those two tables based on the value of the col1 and col2 from tbl2. Following is my query

select * 
from tbl1 left join tbl2
on case when tbl2.col1 like '[0-9]x' then left(tbl1.col1, 1)=left(tbl2.col1, 1)
else tbl1.col1=tbl2.col1 and tbl1.col2=isnull(tbl2.col2, tbl1.col2) end

I got an error "Incorrect syntax near '='". Can anyone tell me why? In addition, I also want to put cases such as (3a, 13xx, …) , (3a, 123x, …) or (3a, 1xxx, …) in consideration. Any anyone shed some light?

Upvotes: 0

Views: 4592

Answers (3)

You could use a cte to build results, something like this:

declare @table_01 table (
  [column_01] [sysname]
  );
declare @table_02 table (
  [column_01] [sysname]
  );
with [builder]
     as (select [table_02].[column_01]
         from   @table_01 as [table_01]
                join @table_02 as [table_02]
                  on left([table_01].[column_01], 1) = left([table_02].[column_01], 1)
         where  [table_02].[column_01] like '[0-9]x'
         union
         select [table_02].[column_01]
         from   @table_01 as [table_01]
                join @table_02 as [table_02]
                  on [table_01].[column_01] = [table_02].[column_01]
         where  [table_01].[column_01] = isnull([table_02].[column_01], [table_01].[column_01]))
select [column_01]
from   [builder]; 

Upvotes: 0

Hart CO
Hart CO

Reputation: 34774

Instead of a CASE statement, you can just use multiple sets of criteria with OR:

select * 
from tbl1 
left join tbl2
on   (tbl2.col1 like '[0-9]x' AND left(tbl1.col1, 1) = left(tbl2.col1, 1))
  OR (tbl1.col1=tbl2.col1 AND tbl1.col2 = isnull(tbl2.col2, tbl1.col2))

Upvotes: 0

Andomar
Andomar

Reputation: 238076

A case statement evaluates to a value, while the on clause expects a condition.

You can turn a value into a condition by comparing it with 1, for example:

case 
when tbl2.col1 like '[0-9]x' and left(tbl1.col1, 1) = left(tbl2.col1, 1) then 1
when tbl1.col1 = tbl2.col1 and tbl1.col2 = isnull(tbl2.col2, tbl1.col2) then 1
end = 1

Upvotes: 1

Related Questions