Just another day I received following question –
“Pinal,
I am from DotNet expertise and I do not know how to convert the logic of IF…THEN into SQL statement, would you please help?
~Rajesh”
I love simple questions as they have simple answers. In SQL Server, we can use a CASE statement to implement IF…THEN. Here is the example of the CASE statement.
Example 1:
If you are logic is as follows:
IF -1 < 1 THEN 'TRUE' ELSE 'FALSE'
You can just use CASE statement as follows:
-- SQL Server 2008 and earlier version solution
SELECT CASE
WHEN -1 < 1 THEN 'TRUE'
ELSE 'FALSE' END AS Result
GO
-- SQL Server 2012 solution
SELECT IIF ( -1 < 1, 'TRUE', 'FALSE' ) AS Result;
GO
If you are interested further about how IIF of SQL Server 2012 works read the blog post.
Well, in our example the condition which we have used is pretty simple, but in the real world the logic can very complex.
You can read more about this subject in the blog post over here: SQL SERVER – Implementing IF … THEN in SQL SERVER with CASE Statements.
Reference:Â Pinal Dave (https://blog.sqlauthority.com)
1 Comment. Leave new
Hi Pinal,
i want to write an sql certification exam will you please share me some points regarding what to prepare and how to prepare and how would be the exam
thanks, sai