Jwalin Khatri

Create Serial Number Column using SQL Server

Posted by: jwalin on: February 18, 2009

this is only for SQL 2005

SELECT CategoryID, CategoryName
    FROM (SELECT Row_Number() OVER(ORDER BY CategoryName DESC) as RowNum, 
                            CategoryID, CategoryName FROM dbo.Categories) Cat

OR

SELECT ROW_NUMBER()  OVER (ORDER BY  Field1) As SrNo, Field1,  Field2 FROM < Table>

if you are using SQL 2000 

 

By using the % (modulo) operator we get rows with the categoryid is odd. This does not perfectly give you everyother row since we could have a missing value (the row could have been deleted). Even worse, your additional search criteria could select data that is not evenly distributed between even and odd ids.

This will work every time:

 DECLARE @tCat TABLE (TID int identity(1,1), CategoryID int,CategoryName varchar(100)) 

INSERT @tCat (CategoryID, CategoryName )
SELECT CategoryID, CategoryName
FROM dbo.Categories 

SELECT CategoryID, CategoryName FROM @tCat

thanx david!!!

Happy Programming !!!!

Leave a Reply

Blog Stats

  • 15,017 hits

  • jwalin: Follow the following steps 1]. open you Page in NOTEPAD. 2]. find the tag 3]. Replace the "body" like body oncontextmenu=”return false;" 4]. Sav
  • cytocine: Halu , how to put that , i mean where to put the part ?? i really dont know i hope you can help me out thanks..
  • elmerdolor: Halu , how to put that , i mean where to put the part ?? i really dont know i hope you can help me out thanks..