IMG-LOGO

How to use Switch Case in TSQL?

andy - 23 Dec, 2020 1601 Views 0 Comment

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.

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 ...