在T-SQL中使用多个结果集和联接

时间:2011-06-27 20:41:50

标签: tsql join multiple-resultsets

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

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语句,而不必像示例中那样对每个结果集进行大量连接。在目前的解决方案中,我加入了大量的列,因为我将它们加在一起

1 个答案:

答案 0 :(得分: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