Sql cursor vs CTE

by iatanasov 11. October 2007 05:18

whith is the best way to grow up with MS SQl Server?

I was doing paging in SQL Server 2000 using Temp Table or Derived Tables. I decided to checkout new function ROW_NUMBER() in SQL Server 2005. ROW_NUMBER() returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition. I have compared both the following query on SQL Server 2005.

SQL 2005 Paging Method

USE AdventureWorksGODECLARE  @StartRow INTDECLARE  @EndRow INTSET    @StartRow = 120SET @EndRow = 140SELECT   
 FirstName, LastName, EmailAddressFROM (SELECT    PC.FirstName, PC.LastName, PC.EmailAddress,ROW_NUMBER()
 OVER(Order BY PC.FirstName, PC.LastName,PC.ContactID) AS RowNumberFROM    Person.Contact PC) PersonContactWHERE  
  RowNumber > @StartRow AND RowNumber < @EndRowORDER BY FirstName, LastName, EmailAddressGO

SQL 2000 Paging Method

USE AdventureWorksGODECLARE  @StartRow INTDECLARE  @EndRow INTSET    @StartRow = 120SET @EndRow = 140CREATE TABLE
 #tables (RowNumber INT IDENTITY(1,1),FirstName VARCHAR(100), LastName VARCHAR(100), EmailAddress VARCHAR(100))
INSERT INTO #tables (FirstName, LastName, EmailAddress)SELECT    PC.FirstName, PC.LastName, PC.EmailAddressFROM   
 Person.Contact PCORDER BY FirstName, LastName, EmailAddressSELECT    FirstName, LastName, EmailAddressFROM   
 #tablesWHERE    RowNumber > @StartRow AND RowNumber < @EndRowDROP TABLE #tablesGO

if you wnat to make your life easiest just use ROW_NUMBE() instead using old temp table( or cursor related solutions).



 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

business | MS SQL

Related posts

Comments

January 22. 2008 19:52

Gravatar

nice artice for sql paging

mark ae

February 5. 2008 14:24

Gravatar

thanks

Ivan Atanasov bg

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

July 6. 2008 05:29

Gravatar

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

About the author

Ivan Atanasov - web developer
E-mail me Send mail Subscribe Feed

Calendar

<<  July 2008  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008 it-coder.com

    Sign in