Ado Sort in ASP
In Classic ASP using ADO, you can sort the data in a Recordset using the Sort property of the Recordset object.
How to Sort ADO Recordset in ASP
The
.Sortproperty lets you specify the field(s) and order (ASCorDESC).Sorting is done in-memory on the recordset after fetching data.
You can sort by one or multiple columns.
Syntax
rs.Sort = "FieldName ASC"or for multiple fields:
rs.Sort = "FieldName1 ASC, FieldName2 DESC"Example: Sorting a Recordset by Name Ascending
<%Dim conn, rs, sqlSet conn = Server.CreateObject("ADODB.Connection")conn.Open "Provider=SQLOLEDB;Data Source=SERVER;Initial Catalog=DB;User ID=USER;Password=PASS;"sql = "SELECT UserID, Name, Email FROM Users"Set rs = Server.CreateObject("ADODB.Recordset")rs.Open sql, conn, 1, 3 ' 1=adOpenKeyset, 3=adLockOptimistic' Sort the recordset by Name ascendingrs.Sort = "Name ASC"Do Until rs.EOF Response.Write rs("UserID") & " - " & rs("Name") & "<br>" rs.MoveNextLooprs.CloseSet rs = Nothingconn.CloseSet conn = Nothing%>Notes
Sorting works only if the cursor type supports it (e.g.,
adOpenKeysetoradOpenStatic).If you try to sort on a forward-only cursor (
adOpenForwardOnly), it will cause an error.Sorting on the SQL side with
ORDER BYis usually more efficient, but.Sortis useful for dynamic sorting after retrieval.
Want a demo on sorting with SQL ORDER BY vs ADO .Sort, or handling sorting errors?