如果我在存储过程中有多个 select 语句,如何使用 SqlDataReader
我在 Microsoft SQL Server 2005 的存储过程中编写了三个 select 语句。两个 select 语句都返回多个记录,并且 select 语句的表列表不同。 一个从主表中选择记录,另一个从子表中选择记录。 在 C# 代码中,我想获取所有这些记录并将所有数据放入一个对象中。 我正在使用 SqlDataReader。 是否可以使用它或者我应该做其他事情。
I have coded three select statements in stored procedure in Microsoft SQL Server 2005. Both select statements return multiple number of records and table list for select statements is different. One select records from a master table and the other from a child table. In C# code I want to get all these records and put all the data in one object. I am using SqlDataReader. Is it possible with it or should i do something else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用NextResult 方法用于导航查询的多个结果。
要循环遍历所有数据,您可以执行如下操作:
因此以此为背景,并假设主结果集首先出现,可以按如下方式填充主数据和详细信息对象:
首先,建立主记录的字典:
下一步,继续详细记录并将其添加到相应的主记录中:
显然,您应该用数据中的内容替换列名称,并提供主对象和详细对象的完整初始化。
如果详细结果集按 master id 排序,则最后一个循环可以优化为仅从字典中查找每个 master 一次。 如果结果集很小,那么收益不会那么大。
You use the NextResult method on the datareader to navigate with multiple results from a query.
To loop through all data you would do something like this:
So with that as a background, and assuming the master resultset comes first, populating master and detail objects could be done like this:
First, build up a dictionary of the Master records:
Next, move on to detail records and add those to their corresponding master:
You should obviously replace column names with what you have in your data as well as supply the full initialization of Master and Detail objects.
If the detail resultset is sorted on master id, the last loop could be optimized to only lookup each master once from the dictionary. If the resultsets are small though, the gain would not be that huge.
Peter 的解决方案致力于解决使用单个 DataReader 检索多个结果的基本问题。 但是,如果您想将数据保存到复制主从表之间关系的对象,则应该使用
DataSet
。DataSet 可以包含多个
DataTable
,并通过允许在表之间创建DataRelation
来提供对表之间固有关系的全面支持。 然后,您可以通过分别从 Master 或 Details 表中调用GetChildRows()
或GetParentRows()
来获取每个场景的相关记录。网上可能有很多示例说明如何执行此操作。 这是我群组中的一个讨论帖,我在其中列出了步骤并提供了一些代码来演示该过程。
Peter's solution works to solve the basic problem of retrieving multiple results with a single
DataReader
. However, If you want to save your data to an object which replicates the relationship between the Master-Details tables, you should be using aDataSet
instead.DataSets can contain multiple
DataTable
s and provide full support for inherent relationships between the tables by allowing creation ofDataRelation
s between the tables. Then you can get related records for each scenario by callingGetChildRows()
orGetParentRows()
from the Master or Details tables respectively.There are probably many samples online that illustrate how to do this. Here's one discussion thread from my Group where I have listed the steps and provided some code to demonstrate the procedure.