Troubleshooting
ODBC SQL Server field reads fail out of order: the forward-only cursor
Short answer
An established SQL Server ODBC connection opens a forward-only, read-only cursor by default, so a field read succeeds only when it moves forward from the last column read, and any second pass fails. Confirm it by reading one record's fields in ascending then descending order; fix it by fetching the whole result into memory with db.QueryToClass instead of stepping a recordset handle.

On this page
- Why do some SQL Server ODBC field reads fail while others succeed?
- What does a forward-only cursor actually allow?
- How do I confirm the failure depends on read order?
- Why does the second pass over the result always fail?
- Should I reorder the reads or fetch the result into memory?
- How do I convert the script and verify the fix?
- What limits apply to the in-memory result?
- When do I stop and escalate?
- Questions asked
A script that reads an ODBC recordset from SQL Server and fails on some db.field calls while others succeed is not hitting a data type problem, a corrupt record or a broken driver. The SQL Server ODBC driver opens every query as a forward-only, read-only cursor by default, so each column can be taken once, moving forward through the result. The same code appears to work against an Access .mdb DSN only because that driver tolerates out-of-order access, and it fails the same way with either the SQL Server driver or the Native Client driver. The durable fix is to fetch the query result into memory instead of stepping a recordset handle.
Why do some SQL Server ODBC field reads fail while others succeed? #
The SQL Server ODBC driver opens every query as a forward-only, read-only cursor by default, so a db.field read succeeds only when the column you ask for sits at or past the last column the driver has already handed you. Microsoft's SQL Server ODBC documentation sets the default cursor attributes at forward-only, read-only and a rowset size of 1, and states that these defaults do not use a server cursor. A forward-only, non-scrollable cursor moves only toward the end of the result set. The driver does not keep the row buffered for random access, so once your script has taken a column, asking for an earlier one returns nothing usable.
That single rule explains every symptom in the reported setup:
- A field fails one run and passes the next: the read order changed relative to the other reads, so a different set of columns happens to land at or past the last one taken.
- Every read fails on the second pass: the first pass consumed the row or the whole result set.
- The record count comes back reliably every time: counting rows only steps forward and never touches field data.
- The SQL Server driver and the Native Client driver behave identically: both default the same way, so changing drivers changes nothing.
What does a forward-only cursor actually allow? #
It allows exactly one movement: fetch the next row, and within that row take the columns in select-list order, once each, because the driver passes each value to your script and keeps no buffer for going back. The ODBC documentation describes this as the typical default cursor type, one that can move only forward through the result set. SQL Server's fast forward-only cursor is implemented much like a default result set, which is why it is fast and equally one-directional. There is no move-to-first, no previous row and no re-read of a column already handed over. Any logic that needs a second look at a value, such as a condition test followed by an assignment, needs the value in a variable or in memory, not a second read from the recordset.
How do I confirm the failure depends on read order? #
Take one record and read the same integer fields twice, once in ascending select-list order and once in descending order, logging every value; if ascending passes and descending fails, the cursor is the cause and you can stop checking the query, the DSN and the login.
| Outcome | Meaning | Next step |
|---|---|---|
| Ascending order passes, descending fails | Forward-only, in-order column access: the cursor is the cause | Convert the result to an in-memory class |
| Both orders fail on the first read | Query, DSN or permissions problem, not a cursor fault | Run the same SELECT in a SQL client with the same login and confirm rows and column names |
| Both pass; only a repeat read fails | The cursor already consumed the row or set | Go straight to the in-memory fix |
Run this check before touching the connection. An out-of-order failure on an established connection is a cursor problem; a connection that refuses before any query runs is a different fault, such as a PI ODBC connection that fails with SQLSTATE 08004 before a query runs, where authentication, DSN or service state decide the outcome.
Why does the second pass over the result always fail? #
The first loop consumes the result set, and a forward-only cursor cannot rewind, so every read on the second pass returns nothing; this is expected behavior, not a corrupt record or a type mismatch. Confirm it by counting fetches: if the first loop reaches the last record and the next loop returns no values, the handle sits at end of set. Re-running the query does give a fresh forward pass, but it costs a round trip to the server and can return different data if rows changed between runs, so it is no substitute for holding the result when the logic needs random access, whether that is comparing neighboring rows, indexing by position or feeding one result to more than one consumer.
Should I reorder the reads or fetch the result into memory? #
Fetch the result into memory: reordering reads into single in-order passes works but breaks silently on the next edit, while pulling the whole result into one class with db.QueryToClass gives random access and survives every later change to the script. The cheap fix reads each column once, in select-list order, into local variables, then works from the variables. It satisfies the cursor, but a later edit to the SELECT list or an added debug print shifts the order and the script breaks silently.
The durable fix is db.QueryToClass(), a call the environment vendor's support reports as reliable even though it is absent from the help file. It works only with SELECT statements and returns the whole result as a class holding one array per selected field, so reads are random-access even though the driver cursor underneath stays forward-only. Take the durable fix: reordering reads only defers the failure to the next edit.
How do I convert the script and verify the fix? #
Keep the db.Open and db.close calls and the handle exactly as they are, replace only the recordset loop with one db.QueryToClass call, then prove the fix by reading the same index three times in mixed order and comparing row counts.
private handle
private result
// connection call unchanged
handle = db.Open(myDsn)
result = db.QueryToClass(handle, "SELECT field1, field2 FROM mydb WHERE station = 3")
? result.field1[0]
db.close(handle)
The returned class exposes three members:
| Member | Contents |
|---|---|
result.fieldname |
One array holding every value of that selected column, indexed by row |
result.FieldNames |
Array of strings listing the returned columns |
result.RecordCount |
Number of rows in the result |
Verify the conversion with these checks:
- Print
result.FieldNamesandresult.RecordCount; names differ from expectation when the SELECT uses aliases or an asterisk. - Compare
result.RecordCountwith the count the old loop reported; the old count was reliable, so it is the reference. - Replace each
db.fieldread with indexed access into the matching array, indexing by row number. - Read the same index three times in mixed order, including the same index twice in a row; every read must return the identical value. That test fails on the old cursor.
- Compare a sample of values against the same SELECT run in a SQL client under the same login.
- Call
db.close(handle)on every exit path, including error paths.
What limits apply to the in-memory result? #
The whole result sits in memory, so size it before you run it: 10,000 rows of four integer columns is 40,000 values, and at roughly 32 bytes per scripting value that is about 1.28 MB, comfortably small, while an unbounded SELECT on a large table is not. Worked example, with the storage figure marked as illustrative:
- Values stored: 10,000 rows × 4 columns = 40,000 values.
- Raw column data: 4 bytes per integer × 4 columns × 10,000 rows = 160,000 bytes ≈ 0.15 MiB (160,000 ÷ 1,048,576 = 0.15).
- Scripting storage at an illustrative 32 bytes per tagged value: 40,000 × 32 bytes = 1,280,000 bytes ≈ 1.22 MiB (1,280,000 ÷ 1,048,576 = 1.22).
The raw figure is what the server sends; the scripting figure is what the in-memory class costs. The 32-byte allowance is an example, not a documented constant: measure it once in your environment and reuse that number. Scale the same way: 500,000 rows of the same four columns is 50 times the scripting storage, about 61 MiB (500,000 × 4 × 32 = 64,000,000 bytes ÷ 1,048,576 = 61.0), which belongs behind a WHERE filter or a row cap such as TOP 5000. The decision rule is rows × columns × your measured per-value storage against the environment's memory budget. Keep INSERT, UPDATE and DELETE statements on the statement-execution path you already use, because the in-memory call accepts only SELECT.
When do I stop and escalate? #
Escalate to the platform vendor's official support when a single in-order read of one column still fails on the first pass, or when the in-memory result returns a row count or values that differ from the same SELECT run in a SQL client under the same login. Send the script, the connection settings and the ODBC driver name, and ask them to confirm the call is supported for your environment version; keep drivers coming only from Microsoft or your database vendor. Everything between those two failure modes is fixed by the conversion above: an order-dependent failure plus a failing second pass on an established connection is the forward-only cursor, and the in-memory result ends it.
Questions asked
Does swapping the SQL Server driver for the Native Client driver change the cursor behavior?
No. Both drivers default to a forward-only, read-only cursor, which matches the documented default for SQL Server ODBC connections, so the same out-of-order reads fail either way. The fix is in how the script consumes the result, not in the driver choice: read each column once in select-list order, or fetch the whole result into memory with db.QueryToClass.
Why does the same code work against an Access .mdb DSN?
The Access driver was observed tolerating out-of-order field reads in this setup, so the script appears to work, but the second read of a record still failed there. Treat the Access path as masking the defect, not fixing it: the same single-read discipline or the in-memory conversion applies if you want code that behaves the same on both backends.
Can db.QueryToClass run INSERT, UPDATE or DELETE statements?
No, it works only with SELECT statements. Keep data-modification statements on the statement-execution path you already use, and reserve db.QueryToClass for queries whose results the script needs to read more than once or out of order. That split also keeps the memory cost tied to result sets the script actually consumes.
How do I list the column names and row count a query returned?
Read the FieldNames member for the returned column names as strings and the RecordCount member for the number of rows. A RecordCount of zero means the WHERE clause matched nothing or the login lacks rights, not a read fault. Compare RecordCount with the count your old row loop reported, which was reliable even while field reads were failing.
How large can the in-memory result be?
Size it as rows times columns times the per-value storage your scripting environment uses for a tagged value. For example 10,000 rows of four integer columns is 40,000 values; at an illustrative 32 bytes per value that is about 1.28 MB. Filter with WHERE, select only the needed columns and cap rows with TOP before running anything bigger.

