moshe moshe - 3 months ago 7
SQL Question

IF condition doesn't work properly

I would like to write a query using

IF
, but its not working , what's wrong with this query?

SELECT
IF(Emp.Name is not null)
((Emp.Name) + '_' + (Emp.LastName)) as ID
else
Emp.ID


I get this error:

Incorrect syntax near the keyword 'IF'.


Why is that?

Thank you.

Answer

You can use CASE EXPRESSION :

SELECT CASE WHEN emp.name is not null THEN emp.name + '_' + emp.lastName 
            ELSE Emp.id 
       END as [ID]
FROM ...

The IF() is performed differently in SQL-Server (I assume by the concat syntax),

IF ( Condition ) 
    SQL STATEMENT
ELSE
    SQL STATEMENT 

Which means you need to perform the entire select in each block. Your kind of IF() is used in MySQL , IF(Condition , THEN , ELSE )