MS SQL Server
  Home arrow MS SQL Server arrow Page 3 - Completing the Introduction to Transact-SQ...
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

Completing the Introduction to Transact-SQL
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 10
    2008-01-08

    Table of Contents:
  • Completing the Introduction to Transact-SQL
  • Error Handling
  • Playing with Cursors
  • The World of Functions

  • 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

    Completing the Introduction to Transact-SQL - Playing with Cursors


    (Page 3 of 4 )

    Playing with Cursors

    You may ask what we can do with cursors. Cursors are really useful because we can access data on a row-by-row basis. Each time we use the SELECT statement, the table is returned as a whole, including all of the rows. However, from time to time a situation may arise where we need to work with rows independently.

    What's more, with the help of cursors we can move throughout the table on a row-by-row basis using the return values of the SELECT statement. That's how we can work on the rows- modify, delete, and so forth. There are specific steps which must be followed when working with cursors:


    1. Declaration of variables to store the return row-values of the SELECT statement.

    2. Declaration of the cursor (by pointing out the appropriate SELECT statement).

    3. Opening the cursor.

    4. Accessing the rows (data) using the cursors.

    5. Closing the cursor (and also de-allocate it if you won't need it anymore).


    Keep in mind that the cursors allow us sequential forward movements only. There's no way you could step backwards. So be aware of how many rows you fetch forward.

    Check out the following real-world example where we implement cursors to print the ProdId, ProdName, and UnitPrice columns of the table called Products.


    Use NameOfDatabase

    -- 1. Declaration of variables.

    DECLARE @MyProdID smallint

    DECLARE @MyProdName nvarchar(20)

    DECLARE @MyUnitPrice smallmoney

    -- 2. Declaration of the cursor.

    DECLARE ProdCursor CURSOR FOR

    SELECT ProdID, ProdName, UnitPrice

    FROM Products

    WHERE ProdID <= 10

    -- 3. Opening the cursor.

    OPEN ProdCursor

    -- 4. Accessing the rows from the cursor.

    FETCH NEXT FROM ProdCursor

    INTO @MyProdID, @MyProdName, @MyUnitPrice

    PRINT '@MyProdID = ' + CONVERT(nvarchar, @MyProdID)

    PRINT '@MyProdName = ' + CONVERT(nvarchar, @MyProdName)

    PRINT '@MyUnitPrice = ' + CONVERT(nvarchar, @MyUnitPrice)

    WHILE @@FETCH_STATUS = 0

    BEGIN

    FETCH NEXT FROM ProdCursor

    INTO @MyProdID, @MyProdName, @MyUnitPrice

    PRINT '@MyProdID = ' + CONVERT(nvarchar, @MyProdID)

    PRINT '@MyProdName = ' + CONVERT(nvarchar, @MyProdName)

    PRINT '@MyUnitPrice = ' + CONVERT(nvarchar, @MyUnitPrice)

    END

    -- 5. Closing and de-allocating the cursor.

    CLOSE ProdCursor

    DEALLOCATE ProdCursor


    As you can see from the above example, the variables that are declared must be of the same data type as the columns from the database. We declare the cursor using the CURSOR FOR... FROM... WHERE construct of code. As soon as the cursor is opened using the OPEN instruction, the SELECT instruction is executed right away.

    Thereafter, as I mentioned at the beginning of this chapter, we use the FETCH instruction to move on a row-by-row basis throughout the table. There's the variable @@FETCH_STATUS which is used in that WHILE loop. It can have one of the following return values: 0 when the FETCH statement was successfully executed; -1 when an error occurred during the FETCH execution; -2 when the required row does not exist.

    The CLOSE statement closes the cursor, freeing up if there are any cursor locks, but leaves it available for reopening. DEALLOCATE removes the cursor from the reference. After de-allocation the cursor can be reopened only if you re-declare it again.

    Oh, and if you really paid attention, then you may have noticed from the example above that I used the two hyphens (--) to introduce comments. They can be used for single-line comments; you just write them at the beginning of the line that's going to be commented. But we can also use multi-line comments with the /* ... */ block. Comments improve the readability of the code; they are not evaluated nor executed.

    More MS SQL Server Articles
    More By Barzan "Tony" Antal


       · This is the second part of my T-SQL series. Thanks for reading and don't forget to...
     

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