2012-10-19 94 views
1

在Asp.net鮮明分頁,我嘗試使用下面的代碼來實現分頁:與ROW_NUMBER()和總數在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得到distinctEMP_NAMEorder byemp_id爲在單ExecuteReader()條目總數沿着

目前,我打電話給ExecuteReader()兩次,第二次是數據,第二次是總計數。

我跟着SQL Server DISTINCT pagination with ROW_NUMBER() not distinct,但無法理解如何在我的代碼中實現它。請幫忙。

回答

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來讀取多個結果集。

1

Row_Number()會殺死你的差異。把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

您不能在相同的查詢級別內引用ROW_NUMBER()列(它需要位於子查詢或CTE中) –