MS SQL Server
  Home arrow MS SQL Server arrow Page 3 - Working wth Variables in Database Interact...
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 
VeriSign Whitepapers 
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

Working wth Variables in Database Interactions with Transact-SQL
By: Jagadish Chaterjee
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 6
    2007-03-19

    Table of Contents:
  • Working wth Variables in Database Interactions with Transact-SQL
  • Retrieving data from a database using a T-SQL script
  • Common scenarios while retrieving data from a database into variables
  • Using T-SQL variables efficiently: continued

  • 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Working wth Variables in Database Interactions with Transact-SQL - Common scenarios while retrieving data from a database into variables


    (Page 3 of 4 )

    In the previous examples, I included a WHERE clause in the SELECT statement to retrieve only a single row. What happens when we miss or exclude a WHERE clause? Let us consider the following example:

    use Northwind
    go
    declare @Lname varchar(20)
    declare @Fname varchar(20)

    select @Lname = LastName, @Fname = FirstName
    from dbo.Employees

    print 'Name of the Employee:' + @Lname + ',' + @Fname
    go

    In the above example, you can observe that I didn't specify any WHERE clause. The SELECT statement tries to retrieve all rows from the table and push them into the same two variables (@Lname and @Fname). But a variable can have only one value at a time. If a new value is assigned to it, the old one vanishes.

    In the above case, each row of values in variables gets replaced by the next row of values until the SELECT statement retrieves the last row. And finally, only the values of the last row will be available in variables!

    Another scenario is the handling of no rows. What happens if no rows are retrieved? Let us consider the following example:

    use Northwind
    go
    declare @Lname varchar(20)
    declare @Fname varchar(20)
    declare @EmpID int

    set @EmpID = 49
    select @Lname = LastName, @Fname = FirstName
    from dbo.Employees
    where EmployeeID = @EmpID

    print 'Name of the Employee:' + @Lname + ',' + @Fname
    go

    There exists no employee with an Employee ID of 49 in the Northwind database. The SELECT statement will not be able to retrieve any rows and thus it simply fills NULLs into the variables. It is always a good practice to test for the NULLs also as follows:

    use Northwind
    go
    declare @Lname varchar(20)
    declare @Fname varchar(20)
    declare @EmpID int

    set @EmpID = 49
    select @Lname = LastName, @Fname = FirstName
    from dbo.Employees
    where EmployeeID = @EmpID

    if @Lname is null
       print 'Employee not found'
    else
       print 'Name of the Employee:' + @Lname + ',' + @Fname
    go

    Using T-SQL variables efficiently

    Now that we understand variables and filling database values into them, we will look into a few tricks for using them efficiently. Let us start with the following script:

    use Northwind
    go
    declare @Lname varchar(400)
    set @Lname = ''

    select @Lname = @Lname + LastName + ', '
    from dbo.Employees

    print @Lname
    go

    In the above script, I declared a variable named "@Lname" and used it recursively (after initializing it). The SELECT simply retrieves every successive value and concatenates it with the value available in "@Lname," and then stores the latest value (concatenated value) into the same variable "@Lname" (adding a comma after every concatenation). The result would be nothing but the list of all employee names separated with commas!

    The above script may not be good to use for listing out too many concatenated strings, as the size of a variable is limited (cursors and tables would be great choices). But it would be a good option for operations such as sum, running sum, and so forth.

    Just for your information, you can display a cumulative or running sum by writing a query as follows:

    SELECT OrderID, sum(UnitPrice * Quantity) Price,
      (SELECT SUM(UnitPrice * Quantity)
       FROM [Order Details] as b
       WHERE b.orderid <= a.orderid) running_sum
    FROM [Order Details] as a
    group by OrderID
    ORDER BY orderid

    The next section will continue our discussion of the efficient use of variables.

    More MS SQL Server Articles
    More By Jagadish Chaterjee


       · Hello guys,This is the first in a series of articles focusing on Transact-SQL...
       · Storing select query result to an array! how's that possible ?
     

    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 6 hosted by Hostway