Verwenden Sie ROW_NUMBER()
und implementieren Sie eine statische Dienstprogrammfunktion (wie GetPaginatedSQL
in meinem Code), die Ihre ursprüngliche SQL-Abfrage automatisch in eine begrenzte/paginierte SQL-Abfrage umschließt.
Dies ist diejenige, die ich verwende:
namespace Persistence.Utils
{
public class SQLUtils
{
/// <summary>
/// Builds a paginated/limited query from a SELECT SQL.
/// </summary>
/// <param name="startRow">Start row</param>
/// <param name="numberOfRows">Number/quatity of rows to be expected</param>
/// <param name="sql">Original SQL (without its ordering clause)</param>
/// <param name="orderingClause">MANDATORY: ordering clause (including ORDER BY keywords)</param>
/// <returns>Paginated SQL ready to be executed.</returns>
/// <remarks>SELECT keyword of original SQL must be placed exactly at the beginning of the SQL.</remarks>
public static string GetPaginatedSQL(int startRow, int numberOfRows, string sql, string orderingClause)
{
// Ordering clause is mandatory!
if (String.IsNullOrEmpty(orderingClause))
throw new ArgumentNullException("orderingClause");
// numberOfRows here is checked of disable building paginated/limited query
// in case is not greater than 0. In this case we simply return the
// query with its ordering clause appended to it.
// If ordering is not spe
if (numberOfRows <= 0)
{
return String.Format("{0} {1}", sql, orderingClause);
}
// Extract the SELECT from the beginning.
String partialSQL = sql.Remove(0, "SELECT ".Length);
// Build the limited query...
return String.Format(
"SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) AS rn, {1}) AS SUB WHERE rn > {2} AND rn <= {3}",
orderingClause,
partialSQL,
startRow.ToString(),
(startRow + numberOfRows).ToString()
);
}
}
}
Die Funktion könnte oben verbessert, ist aber eine erste Implementierung.
Dann in Ihrem DAOs, sollten Sie sein, nur so etwas wie dies zu machen:
using (var conn = new SqlConnection(CONNECTION_STRING))
{
using (var cmd = conn.CreateCommand())
{
String SQL = "SELECT * FROM MILLIONS_RECORDS_TABLE";
String SQLOrderBy = "ORDER BY DATE ASC "; //GetOrderByClause(Object someInputParams);
String limitedSQL = GetPaginatedSQL(0, 50, SQL, SQLOrderBy);
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
cmd.CommandText = limitedSQL;
// Add named parameters here to the command if needed...
adapter.SelectCommand = cmd;
adapter.Fill(ds);
// Process the dataset...
}
conn.Close();
}
Hoffe, es hilft.
siehe diese http://blog.sqlauthority.com/2010/12/15/sql-server-server-side-paging-in-sql-server-2011-a-better-alternative/ –
Lesen Sie nur dies: http://www.asp.net/web-forms/tutorials/data-access/paging-and-sorting/efficiently-paging-through-large-amounts-of-data-vb Es ist ein sehr komplettes Tutorial (VB.NET aber das ist in diesem Fall nicht wichtig). –
@Guilherme bist du * wirklich * immer noch mit sql-server-2000? (Tags) Wenn ja, wird das Ihre Möglichkeiten ein wenig einschränken. –