简体   繁体   中英

Case statement on a join in where clause

I am trying to use a CASE statement inside a WHERE clause for joining 2 tables. I want to evaluate POSITION_NBR2 , if it is blank (null) then I want to join A.POSITION_NBR2 = B.POSITION_NBR Else I want to join A.POSITION_NBR = B.POSITION_NBR , however I am getting syntax errors while trying to run the following:

UPDATE #WORKTABLE
SET SLT_MEMBER = B.NAME
FROM PS_GHS_FTE_SLT A,
     PS_EMPLOYEES B,
     #WORKTABLE C
WHERE 
  CASE WHEN A.POSITION_NBR2  <> '' THEN A.POSITION_NBR2 = B.POSITION_NBR
       ELSE A.POSITION_NBR = B.POSITION_NBR
       END
  AND A.DEPTID COLLATE Latin1_General_BIN = C.DEPTID COLLATE Latin1_General_BIN
  AND B.EMPL_STATUS = 'A'

Use proper JOIN syntax and reasonable table aliases:

UPDATE WT
    SET SLT_MEMBER = E.NAME
FROM PS_GHS_FTE_SLT GFS JOIN
     PS_EMPLOYEES E
     ON E.POSITION_NBR = (CASE WHEN GFS.POSITION_NBR2 <> '' THEN GFS.POSITION_NBR2 ELSE GFS.POSITION_NBR
                          END) JOIN
     #WORKTABLE WT
     ON GFS.DEPTID COLLATE Latin1_General_BIN = WT.DEPTID COLLATE Latin1_General_BIN 
WHERE E.EMPL_STATUS = 'A';

I'm generally not a fan of using CASE for ON and WHERE clauses. In this case, though, it is only selectively choosing one column, so it doesn't bother me so much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM