Saturday, October 22, 2011

Skip and Take the SQL way

In Asp.Net most databound controls having paging built-in to automatically segment long data sets. There are even jQuery grids that have been built to allow paging. The downside to automatic paging is that you’re still querying and returning the entire set of rows even if you’re showing a subset (in most cases).

If you want to truly limit the bandwidth from your database you can implement Skip and Take within your SQL code.
DECLARE @Skip int
DECLARE @Take int

SET @Skip = 0   -- The number of records to skip
SET @Take = 10  -- The number of records to return

SELECT * FROM (
   SELECT ROW_NUMBER() OVER (ORDER BY [t0].[ID], [t0].[Name],
     [t0].[Address]) AS [ROW_NUMBER], [t0].ID, [t0].Name, [t0].Address
   FROM [Company] AS [t0] ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @Skip + 1 AND @Skip + @Take
ORDER BY [t1].[ROW_NUMBER] 

No comments:

Post a Comment