I believe in JAVA we can set the data reader to point to the 1st row of it's result set. I have a SQLDataReader that has over 20 columns and I need to pre-process some columns and calculate some values before I use the entire result set. Is it possible to re-read the data reader after reading it for the first time to get just selected columns? Or will I need to store the results in a data table and read from it later?
3 Answers
From the MSDN docs at https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader
Provides a way of reading a forward-only stream of rows from a SQL Server database.
You can read one row at a time, but you cannot go back to a row once you've read the next row.
You can read columns in a row in any order, any number of times, and skip fields if you want.
while (reader.Read())
{
var a = reader[2]; // you can skip fields
var b = reader[0]; // you don't have to read the fields in order
var c = reader[2]; // you can re-read fields
}
Comments
No it is not possible.
From SqlDataReader on MSDN:
Provides a way of reading a forward-only stream of rows from a SQL Server database.
(emphasis mine)
You can read all the needed data into a collection and iterate over the copy as often as you want.
Comments
Perhaps you could run 2 queries as part of an sproc. 1st query is limited to the fields for precalculated fields, the 2nd for the rest of the fields. Then in your C# make use of the reader.ReadNext method.
Alternatively SQL does support calculated fields, which might make things simpler.
But personally I'd read the whole data into a List<T> for processing...