Case Statement in SQL

10 Flares 10 Flares ×

Case When statement in SQL server is very much similar like switch case statement in C.Below is  SQL Case When statement syntax.

Simple CASE statement in SQL

To understand Case expression in SQL,here is example of Case statement .First of I create table of product.It contains ProductId(Auto increment,Primary key),ProductName,Price,Availability columns. You can use below script to create table as I say.

After Creating table,I will insert few of records manually as shown below query.I insert CPU & SMPS product’s availability=0.Remember if you are building any web application,then these kind of values inserted by user from Web form.

After executing above insert query,You will find below same table on select query of table.


Now,you want to display in your Listview or Gridview or any other databound control,that some of products are “Out of Stock” or “Unavailable”.Then you have to make Stored procedure to display those products.

You can use below Case statement in stored procedure.

Here I make condition that whenever my Availability column’s value=0 then I write “Out of Stock” else I write “In Stock”.
Make sure that you have to write Else and End keywords.!

After executing above statement,You will find your desired answer as shown in below image.
Case-Statement -in-SQL
The main advantage of Case statement of SQL server is that It will create extra column like ProductStatus,so you can easily bind it to your ListView or Gridview.
Case expression is very difficult when you have to make lots of condition.!
Queries,suggestions are always welcomed. 🙂
Related Reading: Find Duplicate Records in SQL Server

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">