More Group Sites
School Rankings
Jobless Net
Better Home
Enviro++


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest Search | Active Topics | Members | Log In | Register

How to select middle rows, last row or paging results with SQL query Options · View
hong
Posted: Sunday, November 28, 2010 10:45:51 AM

Rank: Administration
Groups: Administration

Joined: 11/23/2008
Posts: 335
Points: 711
Location: Australia
With SQL query, we can easily
1) select top records using SELECT TOP <number of rows>;

2) bottom records using DESC order with SELECT TOP <number of rows>;

3) last record using SELECT LAST(<columnName>) AS myColumnName FROM myTable. If the LAST function is not supported. use SELECT columnName FROM myTable ORDER BY columnName DESC LIMIT 1 ;

4) middle records using Where ID between <start row number> and <end row number>.

For more advanced paging results or middle records query, see the following example:
Code:
        int nStart = (Convert.ToInt32(TextBoxPageNumber.Text) - 1) * Convert.ToInt32(TextBoxPageSize.Text) + 1;
        int nEnd = nStart + Convert.ToInt32(TextBoxPageSize.Text) - 1;
        SqlDataSource1.SelectCommand = "With Cust AS (SELECT Email, FirstName," +
        "ROW_NUMBER() OVER (order by Email) as RowNumber FROM Subscriber where Subscribe='True')" +
        "select * from Cust Where RowNumber Between " + nStart + " and " + nEnd;

Alternatively you can use a stored procedure written by by Frank Kerrigan:
Code:
CREATE PROC GetCustomersByPage

@PageSize int, @PageNumber int

AS

Declare @RowStart int
Declare @RowEnd int

if @PageNumber > 0
Begin

SET @PageNumber = @PageNumber -1

SET @RowStart = @PageSize * @PageNumber + 1;
SET @RowEnd = @RowStart + @PageSize - 1 ;

With Cust AS
     ( SELECT CustomerID, CompanyName,
       ROW_NUMBER() OVER (order by CompanyName) as RowNumber
       FROM Customers )

select *
from Cust
Where RowNumber >= @RowStart and RowNumber <= @RowEnd end

END


Code:
exec GetCustomersByPage 10, 1
Sponsor
Posted: Sunday, November 28, 2010 10:45:51 AM
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

ASPNET Theme created by Boskone (Dan Ferguson)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.
This page was generated in 0.208 seconds.