0

我目前在我的存储过程中使用连接来从不同的表中输出元素。一个激进的例子

select a.*, b.*, c.*, d.*, e.*, f.* from tableA a
join tableB b on a.id = b.foreignid
join tableC c on b.id = c.foreignid
join tableD d on c.id = d.foreignid
join tableE e on d.id = e.foreignid
join tableF f on e.id = f.foreignid
where a.id = 1

在我的 C# 代码中将输出映射到实体时,使用它变得非常不方便,因为我必须维护大量样板代码。相反,我会考虑使用多个结果集,以便可以将每个结果集映射到代码中的对象类型。但是,当我的情况不同的结果都相互关联时,我将如何实现这一目标?我能够找到的示例都围绕着从不同的表中进行选择,这些表中的数据与我的外键无关。如果我要在多个结果集中输出我的结果,我唯一能想到的就是这样

select a.* from tableA
where a.id = 1

select b.* from tableB
join tableA a on a.id = b.foreignid
where a.id = 1

select c.* from tableC
join tableB b on b.id = c.foreignid
join tableA on a.id = b.foreginid
where a.id = 1

select d.* from tableD
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1

select e.* from tableE
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1    

select f.* from tableF
join tableE e on e.id = f.foreignid
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1    

但这并不干净,效率低得多(我想,因为有更多的连接语句)是否可以以我尝试的这种方式使用多个结果集?我只是不知道如何在存储过程中编写 sql 语句,而不必像示例中那样对每个结果集进行大量连接。使用当前的解决方案,我得到了很多列,因为我将它们全部连接在一起

4

1 回答 1

0

您实际上可以从单个 SP 返回多个结果集并在 c# 中使用它们,例如查看这篇文章:http: //blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql- and-multiple-result-sets-in-stored-procedures.aspx

这是一个鲜为人知的功能,但听起来像您所要求的。您不必加入它们并将它们作为扁平行集返回,只需获取单独的行集并将它们拼凑在内存中即可。

此外,您可能想阅读 ORM 框架,如果它符合您的需要,这可以节省您在功能上花费的大量打字时间。 https://stackoverflow.com/questions/249550/what-orm-frameworks-for-net-do-you-like-best

问候 GJ

于 2011-06-27T23:25:26.050 回答