SqlDataReader.Read和SqlDataReader.NextResult的区别 [英] Difference between SqlDataReader.Read and SqlDataReader.NextResult
问题描述
这是这两种方法的主要区别?在MSDN网站上它是象下面这样解释,但我不明白。
What is the main difference between these two methods? On the msdn website it is explained like below but I don't understand it.
读
进展SqlDataReader的下一条记录。 (重写
DbDataReader.Read()。)
Read
Advances the SqlDataReader to the next record. (Overrides
DbDataReader.Read().)
NextResult
,使数据读取到下一个
结果,读取批处理的Transact-SQL语句的结果时。 (重写dbDataReader.NextResult()。)
NextResult
Advances the data reader to the next
result, when reading the results of batch Transact-SQL statements. (Overrides dbDataReader.NextResult().)
推荐答案
如果您的语句是在/ proc返回多个结果集,例如,如果您有两个选择
语句在单个命令
的对象,那么你将获得两个结果集。
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
用于结果集之间移动。 -
读
用于向前移动一个结果集中的记录。
NextResult
is used to move between result sets.Read
is used to move forward in records of a single result set.
请看下面的例子:
如果你有一个进程,其主体是这样的:
If you have a proc whose main body is like:
.... Proc start
SELECT Name,Address FROM Table1
SELECT ID,Department FROM Table2
-- Proc End
执行上面的进程内会产生两个结果集。一为表1
或第一个SELECT语句等下一个选择
语句。
Executing the above proc would produce two result sets. One for Table1
or first select statement and other for the next select
statement.
在默认情况下第一个结果集将可用于读
。如果你想要移动到第二个结果集,则需要 NextResult
。
By default first result set would be available for Read
. If you want to move to second result set, you will need NextResult
.
请参阅:检索数据使用DataReader
例子code:使用NextResult检索多个结果集
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();
}
}
}
这篇关于SqlDataReader.Read和SqlDataReader.NextResult的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!