Hi every one i want to use case statement in join using this query and got error
Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID
FROM F_SALESINVOICEITEM SII
INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID
INNER JOIN #TempTableSearch ts ON CASE
WHEN ts.ACCOUNTTYPE = '1' THEN ts.ACCOUNTID=SI.TENANCYID
WHEN ts.ACCOUNTTYPE='2' THEN ts.ACCOUNTID=SI.EMPLOYEEID
WHEN ts.ACCOUNTTYPE='3' THEN ts.ACCOUNTID=SI.SUPPLIERID
WHEN ts.ACCOUNTTYPE='4' THEN ts.ACCOUNTID=SI.SALESCUSTOMERID
Error
Incorrect syntax near '='.
Please help me to solve this error.
you can do this, so you have no chance to misspell something (note that
ACCOUNTTYPE
andACCOUNTID
used only when needed, you don't have to copy-paste it)You have syntax error. You are missing
END
there.Instead of using CASE, I'd much rather do this:
To explain why the query didn't work for you: the syntax of the
CASE
requires anEND
at the end of the clause. It would work, as the other solutions proposed suggest, but I find this version to be more convenient to understand - although this part is highly subjective.IT should be,
You must understand that
CASE ... END
block is NOT equivalent toIF { }
from C-like languages. Much rather this is equivalent to elaborate version of... ? ... : ...
operator from C-like languages. What it means that the WHOLECASE
block must essentially evaluate to single value and that this value has to be the same type no matter which case of the block is executed. This means that:Is fundamentally incorrect unless you work on a version of database that will allow you bool value as a value (SQL Server won't allow it for example but I think some of MySQL version used to allow it - not sure about this). You probably should write something like:
Notice how the whole
CASE
block evaluates to 1 or 0 and then it is compared to 1. Of course instead of 4WHEN
's you could use oneWHEN
with combination ofAND
's,OR
's and( )
brackets. Of course in this particular case answer by @ppeterka 66 is correct asCASE
is not suited for what you really wanted to do - I'm just trying to clarify whatCASE
really is.