Tuesday, August 26, 2008

Selecting Top 'N' number of records from SQL

The following SQL script will help you to retrieve TOP ‘N’ records from SQL table using the stored procedure

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[SelectTopN]

(

@TopN int

)

AS

SET NOCOUNT ON;

SELECT ColumnName1, ColumnName2

FROM (

SELECT ROW_NUMBER() OVER (ORDER BY [ColumnName])AS Row, * FROM (

SELECT ColumnName1, ColumnName2

FROM [TableName]

)

AS UserQuery)

AS SelectionWithRowNumbers

WHERE Row >0 AND Row<=@TopN

No comments: