SQL Server paging query

后端 未结 9 1318
攒了一身酷
攒了一身酷 2021-01-06 16:48

Urggggg! I\'ve been struggling with this for a long time! I can do it with MySQL so easy but not with SQL Server :(

Here are the simplified tables which should be jo

9条回答
  •  不知归路
    2021-01-06 17:28

    You can use the methods from the following class

    internal class PagingHelper
    {
        public static String ParseQueryForPagingAndSorting(String strSQL, string SortExpression, int StartIndex, int EndIndex)
        {
            if (String.IsNullOrEmpty(SortExpression))
                SortExpression = " (select 0)";
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from (");
            sb.Append(" select ROW_NUMBER() OVER (ORDER BY " + SortExpression + ") AS row_num,");
            int index = strSQL.ToLower().IndexOf('t', 0);
            sb.Append(strSQL.Substring(index + 2));
            sb.Append(")");
            sb.Append(" AS TempTable");
            sb.Append(" where row_num>=" + StartIndex.ToString() + " AND row_num<=" + EndIndex.ToString());
            return sb.ToString();
        }
        public static String ParseQueryForCount(String strSQL)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select count(*) from");
            sb.Append("(");
            sb.Append(strSQL);
            sb.Append(")");
            sb.Append(" AS TempTable");
            return sb.ToString();
        }
    }
    

提交回复
热议问题