SQL Server:分页查询

一、分页查询

❓ 需求描述:客户端查询数据库数据并显示在表格中。在数据库中进行一次查询,查询结果有1050条记录,但表格row上限: 100,这时需要给本次查询记录分配 页用来显示?

可以通过固定公式进行计算(c伪代码):

# define TABLE_SHOW_ROW 100

// 在大学学生表student中查询年龄小于19岁的学生信息,并按照日期/时间排序(默认升序)
char sql_stat[] = {"select stu_id, stu_name, stu_age, stu_sex, date_time from student where stu_age < 19 order by date_time"};
int num_of_rec = sql_record_total_query(sql_stat);

char msg_page[1024] = {0};
int page;
int quotient= num_of_rec / TABLE_SHOW_ROW;
int remainder = num_of_rec % TABLE_SHOW_ROW;
if (num_of_rec > TABLE_SHOW_ROW)
{
    if (remainder > 0)
        page = quotient + 1;
    else
        page = quotient;
}
else
{
    page = 1;
}
// 打印查询结果页面信息
sprintf(msg_page, "1 of %d", page);

上一页和下一页业务逻辑(c伪代码)

int offset_val;
int page_now = active_page_get(msg_page);

if (event == click_page_up)        // 当客户端点击上一页
{
    offset_val = (page_now - 1) * TABLE_SHOW_ROW;
    --page_now;
}
else if (event == click_page_down) // 当客户端点击下一页
{
    offset_val = page_now * TABLE_SHOW_ROW;
    ++page_now;
}


char sql_stat[1024] = {0};
sprintf(sql_stat, "select stu_id, stu_name, stu_age, stu_sex, date_time from student "
                  "where stu_age < 19 order by date_time "
                  "OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", offset_val, TABLE_SHOW_ROW);
sql_record_get(sql_stat, record);
table_record_show(record);
sprintf(msg_page, "%d of %d", page_now, page);

二、参考引用

7.3 SQL Server分页查询

热门相关:最强狂兵   特工重生:快穿全能女神      法医娇宠,扑倒傲娇王爷   法医娇宠,扑倒傲娇王爷