views:

155

answers:

2

I have a classic asp webpage written in vbscript that outputs the results from a third-party stored procedure. My user wants the page to display the columns of data in a different order than they come in from the database. Is there an easy and safe way to re-order the columns in an ADO recordset?

I did not write this page and cannot change the SP. What is the minimum change I can make here to get the job done and not risk screwing up all the other stuff in the page?

The code looks something like

dim Conn, strSQL, RS
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ServerName

Set strSQL = "EXEC storedProc @foo = " & Request("fooParam")
'This stored procedure returns a date column, an arbitrary '
' number of data columns, and two summation columns.  We '
' want the two summation columns to move so they appear '
' immediately after the data column '

Set RS = Server.CreateObject("ADODB.RecordSet")
RS.ActiveConnection = Nothing
RS.CursorLocation = adUseClient
RS.CursorType = adOpenStatic
RS.LockType = adLockBatchOptimistic
RS.Open strSQL, Conn, adOpenDynamic, adLockOptimistic

dim A

' ----- '
' Insert some code here to move the columns of the RS around '
' to suit the whim of my user '
' ----- '


' Several blocks of code that iterate over the RS and display it various ways '
RS.MoveFirst
For A = 0 To RS.Fields.Count -1
    ' do stuff '
Next

...

RS.MoveFirst
For A = 0 To RS.Fields.Count -1
    ' do more stuff '
Next

RS.Close : Set RS = Nothing
Conn.Close : Set Conn = Nothing
A: 

Get the column names, then set up an ordering for them:

dim ColumnNames
set ColumnNames = CreateObject( "Scripting.Dictionary" )
For A = 0 To RS.Fields.Count -1
  ColumnNames.Add A, RS.Fields(A).Name
Next

Here, ColumnNames holds the name of the column to use for each position. Applying whatever rules make sense, you can now change the ordering like so:

'' swap order of columns 1 and 2
dim temp
temp = ColumnNames.item( 1 )
ColumnNames.item( 1 ) = ColumnNames.item( 2 )
ColumnNames.item( 2 ) = temp

Finally, to get the new order, print as follows:

For A = 0 To RS.Fields.Count -1
  Response.write( ColumnNames.item( A ) )
Next
dmb
A: 

Why do you need to reorder them? If you KNOW that the output follows a certain pattern:

Date, Data1, DataN, Sum1, Sum2

You have Fields.Count to let you decide how many DataN columns to display, and at which index Sum1 and Sum are located.

thomask