与ROW_NUMBER()的明显分页和ASP.Net中的总计数

时间:2012-10-19 12:47:47

标签: c# sql-server ado.net pagination

在Asp.net中,我尝试使用以下代码实现分页:

String query="SELECT * "+
             "FROM (SELECT Distinct emp_name, emp_address, "+
             "         ROW_NUMBER() OVER(ORDER BY emp_id) AS rownum"+
             "       FROM Employee"+
             "     )as Person "+
             "WHERE rownum>"+ start +" and rownum <="+ end +";

SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();

SqlDataReader reader = cmd.ExecuteReader();

以上代码不会检索Distinct行 如何调整query以获取distinct emp_name order by emp_id 以及单{{1}中的总条目数}}?

目前,我先拨打ExecuteReader()两次查看数据,然后再次拨打总计数。

我关注SQL Server DISTINCT pagination with ROW_NUMBER() not distinct但无法理解如何在我的代码中实现它。请帮忙。

2 个答案:

答案 0 :(得分:1)

Row_Number()会杀死你的Distinct。将您的子查询和行号中的Distinct放在(外部)结果集上(在您有一个不同的集合之后)。

String query="SELECT *, ROW_NUMBER()  OVER(ORDER BY emp_id) AS rownum "+
          "FROM (SELECT Distinct emp_name, emp_address, emp_id "+
          "       FROM Employee"+
          "     )as Person "+
          "WHERE rownum>"+ start +" and rownum <="+ end +"; 

答案 1 :(得分:0)

使用String.Format和原始字符串(@)来避免连接。

String query = String.Format(@"
    select emp_name, emp_address, rownum 
    from (
        select
            emp_name, emp_address,
            row_number() over(order by emp_id) as rownum
        from (
            select distinct emp_name, emp_address
            from employee
        ) s
    ) as Person 
    where rownum > {0} and rownum <= {1}
    ;
    select count(*) as total
    from (
        select distinct emp_name, emp_address
        from employee
        where rownum > {0} and rownum <= {1}
    ) s
    ;    
", start, end);

SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();

SqlDataReader reader = cmd.ExecuteReader();

// gets the first data set
while (reader.Read())
{
    ...
}

// gets the second
reader.NextResult();
reader.Read();
int total = (int)reader["total"];

使用NextResult读取多个结果集。