HOW TO ADD COMPLEX WHERE CLAUSE WITH IF
DB.T1Site =If(HasMyRole,"MY",If(HasCHQRole,"CHQ",""))
Hi Omar,
There's no IF/ELSE in SQL (there is in TSQL, but it can't be used inside SQL statements). For conditions in SELECT output, WHERE clauses etc., you use CASE. There are two variants:
The first:
CASE WHEN condition1 value1 WHEN condition2 value2 ELSE value3 END
So each condition is a full condition like "{MyEntity}.[SomeAttribute] = 'A'". The values are whatever value you need to return.
The second:
CASE variable WHEN casevalue1 value1 WHEN casevalue2 value2 ELSE value3 END
The second variant has a variable/attribute name after the CASE, like "{MyEntity}.[SomeAttribute]" and the value after the WHEN checks the value of that variable/attribute (so like "'A'"). This variant looks more like a traditional case statement in C# etc.
In both cases the number of WHEN statements are variable (at least one, no upper limit), and the ELSE part is optional. Don't forget the END!
A final warning: depending on where you put the CASE statement, the query can become very slow. Especially when you use it in join conditions, or when you add it to a WHEN and the result set isn't already limited a lot, SQL may need to perform full table scans (or full intermediate result set scans), which can hog performance.
Hi @Omar AbdElhadi ,
check this post for SQL where clause-
https://stackoverflow.com/questions/13469558/case-when-condition-in-where-clause
you can use case in where condition.
Hope this will help you.
regards
Rahul
Hello @Omar AbdElhadi ,
In SQL SERVER – How to use ‘if… else’ in ‘where’ clause
You can follow this
https://raresql.com/2013/06/28/sql-server-how-to-use-if-else-in-where-clause/
Hope this link will help you.
Thanks & Regards
Navneet Sharma