Syntax issues with pervasive SQL if statement used to determine left join on clause

117 Views Asked by At

Back Story: I am looking to do a left join based on if a condition is true with an if statement. However if it is false, I want to still join the said table in, but with the same columns or with a new set of columns. This query is being wrote for a Pervasive SQL DB.

This query is fairly large, without this particular issue it executes and returns the data sets as expected. Below is a snapshot of the issue I am currently running into..

SELECT A.ONUM, B.JN, C.SEQ, C.PN
From Z.OH
LEFT JOIN OL A ON Z.ONUM = A.ONUM
LEFT JOIN JH B ON A.ONUM = B.SNUM AND A.OLNUM = B.SLNUM AND B.CLSD <> 'Y'
LEFT JOIN JO C ON IF(A.LC <> 'ZY', B.JN = C.JN, LEFT(B.C_PO, 6) = C.JN OR B.JN = C.JN) AND C.OP_T NOT IN ('Z','C')
WHERE Z.OT <> 'T' AND C.PN NOT IN (SELECT X.PN FROM JH X WHERE B.JN = X.JN)

Again, very summarized version with lots of joins/filters/select statement removed.

I am running into issues on the join with the IF statement. Without the if statement, the query executes as expected. The original join being: B.JN = C.JN AND C.OP_T NOT IN ('Z', 'C')

When executing the query in PCC it would give the following syntax error at the following point: "B.JN << ??? >> = C.JN"

I tried switching over to an OR statement as shown below, but the run time of the query made it an impossible choice.

LEFT JOIN JO C ON 
(B.JN = C.JN) OR (A.LC = 'ZY' AND LEFT(B.C_PO, 6) = C.JN) 
AND C.OP_T NOT IN ('Z','C')

Checking the documentation, it looks like the query on the if statement is following the correct syntax...

1

There are 1 best solutions below

0
On

Most simple solution would be to avoid the IF in the WHERE-clause, and do:

SELECT A.ONUM, B.JN, C.SEQ, C.PN
From Z.OH
LEFT JOIN OL A ON Z.ONUM = A.ONUM
LEFT JOIN JH B ON A.ONUM = B.SNUM AND A.OLNUM = B.SLNUM AND B.CLSD <> 'Y'
LEFT JOIN JO C ON (A.LC <> 'ZY' AND B.JN = C.JN) OR (A.LC = 'ZY' AND (LEFT(B.C_PO, 6) = C.JN OR B.JN = C.JN)) 
                  AND C.OP_T NOT IN ('Z','C')
WHERE Z.OT <> 'T' AND C.PN NOT IN (SELECT X.PN FROM JH X WHERE B.JN = X.JN)