SQL SERVER – How to do IF…THEN in SQL SERVER?

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)

Previous Post
SQL SERVER – A Stored Procedure for Executing SSIS Packages in the SSIS Catalog – Notes from the Field #092
Next Post
SQL SERVER – Adding File to Database in AlwaysOn Availability Group

Related Posts

No results found.

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

    Reply

Leave a Reply Cancel reply

Exit mobile version