MS SQL Server
  Home arrow MS SQL Server arrow Page 4 - How to Use Variables, IF and CASE in Datab...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MS SQL SERVER

How to Use Variables, IF and CASE in Database Interactions with TransactSQL
By: Jagadish Chaterjee
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 20
    2007-03-26

    Table of Contents:
  • How to Use Variables, IF and CASE in Database Interactions with TransactSQL
  • Generating serial numbers (or sequences) and cumulative sums using the UPDATE statement
  • Introducing the IF statement in T-SQL
  • Using WHERE conditions in the IF statement
  • Replacing IF with CASE

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    How to Use Variables, IF and CASE in Database Interactions with TransactSQL - Using WHERE conditions in the IF statement


    (Page 4 of 5 )

    The "IF" conditions can include almost all types of conditions being used as part of a "WHERE" clause. These include SQL operators such as IN, IS NULL, LIKE, BETWEEN..AND, and so forth.

    Let us work with a small example which includes a BETWEEN..AND condition as part of an ELSE-IF ladder. The following is the script:

    use northwind
    go

    declare @EmpSales numeric(12,2)
    declare @EmpID int

    set @EmpID = 3
    set @EmpSales = (select sum(unitprice * quantity)
                     from [order details]
                     where orderid in (select orderid from orders
                                       where employeeid=@EmpID))
    if @EmpSales < 100000
       print 'Bad sales: ' + convert(varchar, @EmpSales)
    else if @EmpSales between 100000 and 200000
       print 'Normal sales: ' + convert(varchar, @EmpSales)
    else
       print 'Good sales: ' + convert(varchar, @EmpSales)
    go

    From the above code, you can observe that I am working with an ELSE-IF ladder (it can include any number of steps) together with a BETWEEN..AND condition. Any IF structure can be nested any number of times.

    The IF condition with SELECT statements

    An IF condition can even include SELECT statements. This is a bit different from the traditional approach of IF conditions. Let us examine the following script:

    use northwind
    go

    declare @EmpSales numeric(12,2)
    declare @EmpID int

    set @EmpID = 2
    set @EmpSales = (select sum(unitprice * quantity)
                     from [order details]
                     where orderid in (select orderid from orders
                                       where employeeid=@EmpID))
    if @EmpSales < (select avg(unitprice * quantity)
                    from [order details])
       print 'Bad sales: ' + convert(varchar, @EmpSales)
    else
       print 'Good sales: ' + convert(varchar, @EmpSales)
    go

    According to the above script, the value of "@EmpSales" is checked against the average price of all orders. We can even include two SELECT statements in the same condition as follows:

    use northwind
    go

    declare @EmpID int

    set @EmpID = 2
    if (select sum(unitprice * quantity)
        from [order details]
        where orderid in (select orderid from orders
                          where employeeid=@EmpID))
     < (select avg(unitprice * quantity)
        from [order details])
       print 'Bad sales'
    else
       print 'Good sales'
    go

    Testing for row existence in a table is a frequently used feature in T-SQL programming. The EXISTS operator available as part of SQL can also be used here to test for the same. The following is an example:

    use northwind
    go

    declare @EmpID int
    declare @Ename varchar(20)
    set @EmpID = 2
    if exists (select * from Employees
               where EmployeeID = @EmpID)
       print 'Employee found'
    else
       print 'Employee not found'
    go

    More MS SQL Server Articles
    More By Jagadish Chaterjee


       · Hello guys,This is second in series focusing on the programming with...
       · I was able to retrieve value of a column which is not updated!Declare @Location...
       · Wow that is great. I'm going to try a couple of tricks and see what happens. ...
     

    MS SQL SERVER ARTICLES

    - Completing the Introduction to Transact-SQL
    - A Brief Introduction to Transact-SQL
    - Lookups and Blocking Bad Data
    - Field Validation Rules for Blocking Bad Data
    - Using Masks to Block Bad Data
    - Blocking Bad Data
    - Using @@ROWCOUNT and TABLE Variables for Dat...
    - How to Use Variables, IF and CASE in Databas...
    - Creating Important Aspects of Notification S...
    - Working wth Variables in Database Interactio...
    - Delving Deeper into Notification Services
    - Notification Services
    - Building a Multi-table Report with SQL 2005 ...
    - A Secure Way of Building Connection Strings
    - Transferring a Database Using the SSIS Desig...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway