SQL Server gives us facility to fetch or modify records on condition basis. Suppose we have an “Order” table and we need to fetch records with conditions if user order price is less than 200 Rs it means user is “silver”, if price is greater than 200Rs and less than 500Rs it means user is Gold same like this if price is greater than 500Rs it means user is “Platinum” .
We can easily solve this problem using SQL Server.
Example:
CREATETABLE#Order( IDINTIDENTITY(1,1)PRIMARYKEY, USR_NAMEVARCHAR(100), SKUVARCHAR(100), QTYINT, PRICEDECIMAL(18,2), CREATED_DATEDATETIME ) INSERTINTO#Order(USR_NAME,SKU,QTY,PRICE,CREATED_DATE) SELECT'User1','9876543210',2,200,GETDATE() UNIONALL SELECT'User2','9876543210',2,300,GETDATE() UNIONALL SELECT'User3','9876543210',2,400,GETDATE() UNIONALL SELECT'User4','9876543210',2,550,GETDATE() --Case statement SELECTUSR_NAME,PRICE, ( CASE WHENPRICE<=200 THEN'SILVER' WHENPRICE>200 ANDPRICE<=500 THEN'GOLDEN' WHENPRICE>500 THEN'PLATINUM'ELSE'NULL'END )ASUSER_TYPE FROM#Order DROPTABLE#Order |
The basic formulations for CASE Expression
Simple Case Expression: Simple case expressions check one expression against multiple values. Simple case expressions allow only an equality check.
Example:
DECLARE@valueINT=2 SELECTCASE@valueWHEN 1 THEN'ONE' WHEN 2 THEN'TWO' WHEN 3 THEN'THREE' ELSE'NOT MATCH' END |
Searched Case Expression: Searched Case Expression allows comparison operators. The simple CASE expression checks only for equivalent values and can’t contain Boolean expressions.
Example:
DECLARE@valueINT=20 SELECTCASEWHEN@value<20 THEN'SILVER' WHEN@value>=20 AND@value<=50 THEN'GOLDEN' WHEN@value>50 THEN'PLATINUM' END |