Published on: 17 Nov, 2020

How to use if condition in TSQL?

Tumblr Digg Google Plus

Learn how to use if condition in TSQL. The conditioning feature is used when you want to ensure only a specific or procedure to be executed if it meets the condition you specify. Please see how the If condition SQL syntax is used.


IF Boolean expression for comparison
     { SQL statement block }
ELSE 
     { SQL statement block }

Let's go ahead with the example. Here is an example of the situation that we want to apply this If condition.

  • We have two product tables and want to show the first product table only if the current date has not reached the mid of the month.
  • If it is already reached the mid of the month. We want to show the second product table.
  • To identify if the current day has not reached the mid-day is by getting the total days of the current month, divided the total by 2 and then plus 1 day. For example: If today's month is December which has 31 days. The midday will be the 15th. We will use the CEILING function in TSQL so we will get the higher number which will return 17 for passing the mid of the month.
     

Here is the SQL query to solve the above situation. To make it easier to understand, we have divided the SQL query into multiple sections.


-- In this example, the current month is Nov which will return 16 (Nov has 30 days in a month)
DECLARE @EndOfMonth DATE = EOMONTH(GetDate())
DECLARE @CurrentDay INT = DAY(GetDate())
DECLARE @MidDay INT = 0
SELECT	@MidDay =CEILING(DAY(@EndOfMonth)/ 2.00) + 1

SELECT	@EndOfMonth AS EndOfMonth,  
		@CurrentDay AS CurrentDay, 
		@MidDay AS MidDay

IF @CurrentDay <= @MidDay
	SELECT 'The current day has not passed the mid month.' AS IfConditionResult
ELSE
	SELECT 'The current day has passed the mid month.' AS IfConditionResult


Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.