CASE Statements in SQL Server

CASE Statements:

SQL CASE is a very unique conditional statement providing if/then/else logic for any ordinary SQL command, such as SELECT or UPDATE.

It provides the ability to manipulate the presentation of the data without actually updating or changing the base table.
It masks the actual values present in a table to end users without altering the data in base table. And provides the necessary information needed by the particular end users.

Syntax:
Select
column_name, ‘new_column_name’=CASE
WHEN (Condition)
THEN
“msg to display / any computation”
ELSE
Some other output
END

Sample code:
Select
  Product, ‘Status’=CASE
WHEN
Quantity>0
THEN
 “In-stock”
ELSE
 “Out-of-stock”
END
 From
 dbo.inventory

Explanation: 
This query displays the product and status of the quantity of product whether its in-stock or out-of-stock by checking a condition quantity>0, instead of displaying the actual amount of quantity.
It provides an online catalog to allow users to check the status of items without disclosing the actual amount of inventory the store currently has in stock.

0 comments:

Post a Comment

Blogger news