Difference between SqlDataReader.Read and SqlDataReader.NextResult

后端 未结 2 1888
花落未央
花落未央 2020-12-09 14:52

What is the main difference between these two methods? On the msdn website it is explained like below but I don\'t understand it.

Read Advances the Sql

相关标签:
2条回答
  • 2020-12-09 15:21

    If your statement/proc is returning multiple result sets, For example, if you have two select statements in single Command object, then you will get back two result sets.

    • NextResult is used to move between result sets.
    • Read is used to move forward in records of a single result set.

    Consider the following example:

    If you have a proc whose main body is like:

    .... Proc start
    
    SELECT Name,Address FROM Table1
    
    SELECT ID,Department FROM Table2
    
    -- Proc End
    

    Executing the above proc would produce two result sets. One for Table1 or first select statement and other for the next select statement.

    By default first result set would be available for Read. If you want to move to second result set, you will need NextResult.

    See: Retrieving Data Using a DataReader

    Example Code from the same link: Retrieving Multiple Result Sets using NextResult

    static void RetrieveMultipleResults(SqlConnection connection)
    {
        using (connection)
        {
            SqlCommand command = new SqlCommand(
              "SELECT CategoryID, CategoryName FROM dbo.Categories;" +
              "SELECT EmployeeID, LastName FROM dbo.Employees",
              connection);
            connection.Open();
    
            SqlDataReader reader = command.ExecuteReader();
    
            while (reader.HasRows)
            {
                Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
                    reader.GetName(1));
    
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
                        reader.GetString(1));
                }
                reader.NextResult();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 15:40

    Not strictly an answer to this question but if you use the DataTable.Load method to consume data from the reader rather than Reader.Read note that after the Load method has completed, the reader is now placed at the start of the next result set so you should not call the NextResult method otherwise you will skip the next resultset.

    A simple loop on Reader.HasRows around a DataTable.Load call is all that you need to process potential multiple resultsets in this scenario.

    0 讨论(0)
提交回复
热议问题