0

I have the following code that I use to process data from two tables, but I can't seem to make two SqlDataReaders to work with it. Any idea how to change it to make it work?

//SqlConnection cn = valid SQL Server 2008 connection

using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1", cn))
{
    using (SqlDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            int nVal1 = rdr.GetInt32(0);
            int nVal2 = rdr.GetInt32(1);
            //...
            int nValN = rdr.GetInt32(N);

            //Now I process the data read ...

            //After processing I need to use the results
            //to look up data from another table using 
            //this item's data

            using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM table2 WHERE " + strSQLCondition, cn))
            {
                //But code below doesn't let me create another reader
                using (SqlDataReader rdr2 = cmd2.ExecuteReader())
                {
                    while (rdr2.Read())
                    {
                        //Process results
                    }
                }
            }

        }
    }
}
0

1 Answer 1

3

By default, you can only use one active dataset on a connection. You have a few options. The three that come to mind are

  1. Look up the data before hand and cache it
  2. Use a second connection object for your inner command
  3. Use MARS - http://msdn.microsoft.com/en-us/library/ms131686.aspx
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Opening another connection helps. I don't know why I didn't think of it myself :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.