1

在 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_nameorder by emp_id以及 single 中的条目总数ExecuteReader()

目前我打电话ExecuteReader()两次,第一次是数据,第二次是总数。

我遵循SQL Server DISTINCT 分页,其中 ROW_NUMBER() 不明显,但无法理解如何在我的代码中实现它。请帮忙。

4

2 回答 2

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 +"; 
于 2012-10-19T13:35:49.037 回答
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读取多个结果集。

于 2012-10-19T13:38:57.383 回答