大家好,又见面了,我是你们的朋友全栈君。
下文将为您介绍三种SQL分页语句写法,如果您也遇到过类似的问题,不妨一看,相信对您会有所启迪。
SQL分页操作是经常会遇到的,下面就将为您介绍三种SQL分页语句,供您参考,希望对您学习SQL分页能够有所帮助。
方法一(适用于 SQL Server 2000/2005)
SELECT TOP 页大小 * FROM table1 WHERE id NOT IN ( SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id ) ORDER BY id 方法二(适用于 SQL Server 2000/2005)
SELECT TOP 页大小 * FROM table1 WHERE id > ( SELECT ISNULL(MAX(id),0) FROM ( SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id ) A ) ORDER BY id 方法三(适用于 SQL Server 2005)
SELECT TOP 页大小 * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1 ) A
WHERE RowNumber > 页大小*(页数-1)
———————————————————-
/// <summary> /// 将原始SQL语句改造成支持分页的SQL语句 /// </summary> /// <param name=”sql”>原始sql语句</param> /// <param name=”page”>第几页</param> /// <param name=”pageSize”>每页多少记录</param> /// <param name=”primaryField”>原始sql语句主键字段</param> /// <returns></returns> string GetPageSql(string sql, int page, int pageSize,string primaryField) { StringBuilder pageSQL = new StringBuilder(); pageSQL.Append(string.Format (“SELECT TOP {0} * From “,pageSize )); pageSQL.Append(” ( “); pageSQL.Append(string.Format (” SELECT ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber,* FROM “,primaryField )); pageSQL.Append(string.Format(“({0}) tempTable1”, sql)); pageSQL.Append(” ) tempTable2 “); pageSQL.Append(string.Format(” WHERE RowNumber > {0}*({1}-1) “,pageSize , page)); return pageSQL.ToString(); }
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/179166.html原文链接:https://javaforall.cn