HOW TO USE CASE EXPRESSION IN SQL SERVER.

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
 582  View(s)
Ratings:
Rate this:
i wnat to use Case Expression in sqlserver.please help me. 
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to use Case Expression in SQL Server.

    Sometimes, you required to fetch or modify the records based on some conditions. In this case, you may use cursor or loop for modify your records. In this situation Case expression is best alternative for Cursor/looping and also provides better performance.
    You can use CASE expressions anywhere in the SQL Query like CASE expressions can be used with in SELECT statement, WHERE clauses, Order by clause, HAVING clauses,Insert, UPDATE and DLETE statements.
    This compares an expression to a set of simple expressions to find the result. This expression compares an expression to the expression in each WHEN clause for equivalency. If the expression with in the WHEN clause is matched, the expression in the THEN clause will be returned.

     

    Syntax:
    

       CASE expression

    WHEN expression1 THEN Result1

    WHEN expression2 THEN Result2

    ELSE ResultN

    END

    Example :

    select CustomerID,CustomerName,Address,City,PostalCode,Country,

    (case when CustomerID=1 then 'First Record'

    when CustomerID=2 then 'Second Record' end) expcase    from Customer

     


     

     

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!