Вы можете прочитать весь набор записей в массив, используя GetRows
:
'GetDataSet
' Returns a table of data based on the supplied SQL statement and connection string.
'Parameters:
' sqlString (string) - The SQL string to be sent. This can be either a valid SQL string or an Application setting
' specified using the '@' prefix (e.g. @GET_USERNAME)
' connString (string) - The database connection string. Either a valid connection string, an Application setting
' (using the '@' prefix, e.g. @CONN_STRING) or an AMC (AppModeConnection string).
'Usage:
' dataSet = GetDataSet(sqlString, connString)
'Description:
' This function generates a table of information in a 2 dimensional array. The first dimension represents the columns
' and the second the rows. If an error occurs while the routine is executing the array and the base index (0,0) is set
' to C_ERROR, (0,1) to the VBScript error index, and (0,2) to the VBScript error description.
'Notes:
' Updated this function to take advantage of the AppModeConnection feature.
'Revisions:
' 30/09/2015 1.1 Added facility to allow recovery of Application settings as Query and connection strings using
' '@', (e.g.: ds = GetDataSet("@GET_USER_DETAIL", "@CONN_DATABASE")
' 25/09/2015 1.0 Added AMC support for Classic ASP. The system will test to see if there is a valid connection
' string based on the current application mode and the connection string provided (e.g. if the
' connection string is 'CONN_DATABASE' and the application mode is 'DEV' then the final connection
' string will be 'CONN_DATABASE_DEV'. A connection string should be present to cover this.
' < 25/09/2015 0.1 Bug ironed out that prevented closing of the database.
' < 25/09/2015 0.0 Initial version.
function GetDataSet(ByVal sqlString, ByVal connString)
'Test to see if there's an application connection string first...
If Left(connString, 1) = "@" Then
connString = Application(Mid(connString, 2))
Else
Dim amc
amc = AppModeConnection(connString)
If amc <> "" then connString = amc
End If
'Test the SQL string to see if it's stored as an Application setting...
If Left(sqlString, 1) = "@" Then sqlString = Application(Mid(sqlString, 2))
'Define the initial output...
dim rV, rs
If (Application("APP_MODE") = Application("MODE_DEV") And Application("DEV_TRAP_ERRORS")) Or _
(Application("APP_MODE") <> Application("MODE_DEV")) Then On Error Resume Next
'Define and open the recordset object...
set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open sqlString, connString, 0, 1, 1
'Initialise an empty value for the containing array...
redim rV(0,0)
rV(0,0) = C_NO_DATA
'Deal with any errors...
if not rs.EOF and not rs.BOF then
'Store the data...
rV = rs.GetRows()
'Tidy up...
rs.close
set rs = nothing
select case err.number
case 3021 'No data returned
'Do nothing as the initial value will still exist (C_NO_DATA)
case 0 'No error
'Do nothing as data has been returned
case else
redim rV(4,0)
rV(C_COL_IDENTIFIER,0) = C_ERROR
rV(C_COL_ERROR_ID,0) = err.number
rV(C_COL_ERROR_MESSAGE,0) = err.description
rV(C_COL_SQL,0) = sqlString
rV(C_COL_CONNECTION,0) = "Withheld"
end select
end if
on error goto 0
'Return the array...
GetDataSet = rV
end function
Это мой собственный в глубине версии, которая делает некоторые фанки вещи с соединительными струнами и т.д., так что не стесняйтесь использовать его, но примечание что вам придется настраивать обработку строк подключения и т. д. Внутри кода, однако, есть основной элемент - нужный GetRows
.
Вам не нужно устанавливать какие-либо переменные сеанса, просто обрабатывайте все на одной странице, как и marekful's answer, на ваш пост. Вы можете сделать это, используя простой цикл For...Next
, используя массив.
Для использования функции выше, просто объявить SQL и называть это как так ...
Dim ds, sql
sql = "EXEC prc_get_report_data "
ds = GetDataSet(sql, "@my_conn")
(Примечание: прочитать код комментарии о строках подключения).
Массив, возвращаемый из этого, очевидно, двухмерная с нуля, где х = столбцы, у = строки:
ds(x, y)
То, что я, как правило, сделать это определить константы для покрытия имен столбцов, сопоставляя их к эквивалентов в базе данных ...
Const COL_ID = 0 'Column 0 is the ID field (note zero based)
Const COL_TITLE = 1 'Title field
Const COL_DESCRIPTION = 2 'Description field
... и так далее.
Тогда вы можете ссылаться на них eaasily:
If ds(COL_ID, row) = 14 Then
Используйте функцию UBound
, чтобы получить экстентов массива ...
Dim row, rows
For rows = 0 To UBound(ds, 2) '2 is the second dimension of the array (note not zero based
If ds(COL_ID, row) = avalue Then
Вы получаете идею.
Какой тип курсоров вы используете в своем objCon? https://msdn.microsoft.com/en-us/library/windows/desktop/ms681771(v=vs.85).aspx Если это adOpenStatic, вы можете переместить курсор обратно в начало, например. objRS.MoveFirst – Dijkgraaf
У меня есть сложный класс данных, который поддерживает отсоединенные наборы записей, либо возвращение recordcounts (где записи устанавливаются в objRecordset.CacheSize \t \t = 20 objRecordset.CursorLocation \t = adUseClient objRecordset.LockType \t \t = adLockReadOnly) -> Очевидно, мне нужно перейти к первому набору записей из нескольких наборов записей, на которые выводится не только первая запись одного набора записей. Я думаю использовать JS для копирования таблицы по ID в Excel, если я не могу легко создать КОПИЮ набора записей. – MonkeyMagix