Home > SQL Server Tips > Database Development > Using an arbitrary TOP value in SQL Server 2000
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

DATABASE DEVELOPMENT

Using an arbitrary TOP value in SQL Server 2000


Serdar Yegulap, Contributor
08.04.2005
Rating: -4.00- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


This tip was submitted to the SearchSQLServer.com tip library by Serdar Yegulalp. Please let others know how useful it is via the rating scale at the end of the tip. Do you have a useful tip, timesaver or workaround? Submit it today!


In T-SQL, the TOP keyword is used to return a fixed number of records in a query:

SELECT TOP 50 [ID] FROM OurUsers

This query would return only the first 50 matches; everything after that would simply not be returned.

TOP is useful for limiting the scope of a query. For instance, you may return paginated results, but how useful they are may be limited by the fact that they can't accept a variable in the context of a stored procedure. For instance, this would not be a legal statement, where @ROWS is a parameter passed in the context of a stored procedure

SELECT TOP @ROWS [ID] FROM OurUsers

SQL Server 2005 apparently will allow variables to be used as an argument for TOP -- but what if you have no plan to upgrade? To get around this limitation, depending on the scope of what you're trying to do, here are some options:

1. Create a dynamic SQL statement rather than use a stored procedure: This statement could be passed from a program (such as an ASP script) or generated dynamically within a stored procedure. But performance is the downside of this option; each dynamic SQL statement has to be syntax-checked and compiled before running. If performance is not the biggest consideration, this is easy enough.

2. Use the SET ROWCOUNT command: SET ROWCOUNT works like TOP in that it limits the number of records returned. The difference between the two is that SET ROWCOUNT affects everything in the current connection, but, more importantly, it accepts a variable. A sample script might work like this:

SET ROWCOUNT @ROWS
SELECT [ID] FROM OurUsers
SET ROWCOUNT 0

The ROWCOUNT 0 statement returns things to normal so future queries passed in the same connection aren't subject to the same stricture. If you're working with a derived query, you can insert the ROWCOUNT-constrained results into a temporary table, which can then be dropped when you're done. (In a stored procedure, a temporary table would be dropped automatically, which is even more convenient.)

Do you have comments on this tip? Let us know.

About the author: Serdar Yegulalp is editor of the Windows Power Users Newsletter. Check it out for the latest advice and musings on the world of Windows network administrators -- and please share your thoughts as well!


More information from SearchSQLServer.com

  • Tip: Add T-SQL functions to SQL Server system schema
  • Ask the Experts: Ask Andrew Novick your developer questions
  • Topic: Look up SQL Server stored procedures


  • Rate this Tip
    To rate tips, you must be a member of SearchSQLServer.com.
    Register now to start rating these tips. Log in if you are already a member.




    Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



    RELATED CONTENT
    SQL/Transact SQL (T-SQL)
    Using DELETE and TRUNCATE TABLE statements to delete data in SQL Server
    SQL language crash course (just enough to be dangerous)
    Working with IntelliSense in SQL Server 2008 Management Studio
    SQL Server Mailbag: Stored procedures, triggers and SSRS reports
    Working with sparse columns in SQL Server 2008
    Determining the source of full transaction logs in SQL Server
    New GROUP BY option provides better data control in SQL Server 2008
    Using the OPENROWSET function in SQL Server
    Loading data files with SQL Server's BULK INSERT statement
    Importing and exporting bulk data with SQL Server's bcp utility
    SQL/Transact SQL (T-SQL) Research

    Database Development
    Using DELETE and TRUNCATE TABLE statements to delete data in SQL Server
    Speed up reports in SQL Server Reporting Services with caching
    Data Transformation Services vs. SSIS: The key differences
    Working with IntelliSense in SQL Server 2008 Management Studio
    Top tips and tricks for SQL Server database development
    Managing the development lifecycle with Visual Studio Team System 2008
    Processing XML files with SQL Server functions
    A first look at Visual Studio Team System 2008 Database Edition
    How to create a SQL inner join and outer join: Basics to get started
    New datetime data types in SQL Server 2008 offer flexibility

    RELATED GLOSSARY TERMS
    Terms from Whatis.com − the technology online dictionary
    ACID  (SearchSQLServer.com)
    Collaboration Data Objects  (SearchSQLServer.com)
    commit  (SearchSQLServer.com)
    container  (SearchSQLServer.com)
    DAO  (SearchSQLServer.com)
    fetch  (SearchSQLServer.com)
    OLE DB  (SearchSQLServer.com)
    query  (SearchSQLServer.com)
    SQL  (SearchSQLServer.com)
    T-SQL  (SearchSQLServer.com)

    RELATED RESOURCES
    2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
    Search Bitpipe.com for the latest white papers and business webcasts
    Whatis.com, the online computer dictionary

    DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



    SQL Server Development - .NET, C#, T-SQL, Visual Basic
    HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
    About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
    SEARCH 
    TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

    TechTarget Corporate Web Site  |  Media Kits  |  Site Map




    All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
      TechTarget - The IT Media ROI Experts