Alexander
Alexander

Reputation: 20224

Jump to specific data row in SqlDataReader

In my result, I want to jump arbitrarily between the rows.

In my table, I have a field next_set. I start at row 1, which has next_set=3, so I process row 3 next, which tells me to look at row 2 afterwards, and so on.

In php/mysql I did this with mysql_data_seek. How do I achieve it in C# / SQL Server?

Upvotes: 0

Views: 1098

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

SqlDataReader is forward-only, it does not allow jumping arbitrarily. However, you have several approaches that you could take here to overcome this problem:

  • Read the data into a DataSet object which allows navigation of its DataTable objects, or
  • Read the data into an array, and navigate using array indexes.

Upvotes: 2

Szymon
Szymon

Reputation: 43023

You cannot jump to some arbitrary position with SqlDataReader. From MSDN description:

Provides a way of reading a forward-only stream of rows from a SQL Server database.

You can only move forward one step at the time.


To get around the issue:

  1. You can either read all records into memory and seek in memory collection.

  2. Use a DataTable to get all records at once.

Upvotes: 2

Related Questions