IMG-LOGO

How to use if condition in TSQL?

andy - 17 Nov, 2020 827 Views 0 Comment

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.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...