日期:2014-05-18  浏览次数:20527 次

sql语句如何实现分页?
整个数据是可以取出来的(量表用full join 之后按时间列排序 最终得到一个完整的“虚拟表”),sql语句如下
C# code

select * from(select * from Orders where Projectid=16) a  full join (select * from PatientCome where RealProjectID=16) b  on a.GUID = b.ComeGUID
order by (case when DialogueTime is null then ComeTimeC else DialogueTime end) desc



通过这条sql语句,我们可以把它当成一个表来处理了,现在我想实现一个分页功能,就拿上面的sql语句举例,我现在有两个变量,一个是“当前页”,另一个是“界面显示条数”。比如 当前页面的变量值为5,界面显示条数为30.
应该怎样修改上面的sql语句呢?(换句话说 第五页的30条数据显示出来)。

PS:貌似网上分页的都是用存储过程,我想知道分页这个功能用存储过程比sql语句的好处是什么?暂时打算只用sql语句实现,至于存储过程,可以sql语句写好之后我再修改出来。当然 如果能sql语句和存储过程都写出来那就更好了。。。

------解决方案--------------------
row_number
------解决方案--------------------
SQL code
类似这样
select * from (
select  ROW_NUMBER() over(order by GUID )rn,* from tab )a where rn between 4 and 6
4、6  换成你的参数

------解决方案--------------------
SQL code

create proc usp_test
    @curr_page int,
    @page_row_num int
as
begin
    set nocount on;

    select * 
    from (select row_number() over (order by (case when DialogueTime is null then ComeTimeC else DialogueTime end) desc) as row_id, * 
          from(select * from Orders where Projectid=16) a  
              full join (select * from PatientCome where RealProjectID=16) b  
                  on a.GUID = b.ComeGUID) c
    where c.row_id > @page_row_num*(@curr_page - 1) and 
          c.row_id <= @page_row_num*@curr_page;
end;
go