Published on: 23 Dec, 2020

How to use Switch Case in TSQL?

Tumblr Digg Google Plus

If you do not want to use the IF condition in TSQL. You can use the Switch Case which is more structured organized.

Here is the basic Switch Case format in SQL Server.


CASE
	WHEN {{ condition expression}} THEN {{ result expression }} 
	ELSE {{ other expression - Optional ]   
END

You can have more than one WHEN condition while the last ELSE condition is optional. Let's say we have the following Products table and we want to display the price description based on the product amount. Anything below $100 will be considered Affordable while between $100 and $200 will be considered Quite Expensive and over $200 will be considered Expensive.

Here is the Switch Case condition code that we will handle the logic condition for the above criteria.


SELECT 	*,
		CASE
			WHEN Price <= 100 THEN 'Affordable'
			WHEN Price > 100 AND 200 <= Price THEN 'Quite Expensive'
			ELSE 'Expensive'
		END AS PriceDescription
FROM [dbo].[Products]

Comments

There are no comments available.

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