2011-06-27 133 views
0

我目前在存儲過程中使用連接來輸出不同表中的元素。一個積極的例子在T-SQL中使用多個結果集並結合連接

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  

但這不是清潔,多了很多ineffecient(我會想,因爲有很多更加入語句) 是否有可能以這種方式使用多個結果集我試圖?我只是不知道如何在存儲過程中編寫sql語句,而無需像示例中那樣按結果集進行大量連接。並配備了目前的解決方案,我得到列的爆炸,因爲我加入他們一起

回答

0

實際上,你可以從一個單一的SP返回multiplte結果集,並在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

+0

我知道如何消費多個結果在我的代碼,如果我能我會使用ORM。但是我們所有的數據庫訪問都使用存儲過程。我確實使用linq to sql來使用我的存儲過程,但這實際上並不能給我一個ORM的全部功能。我的問題是關於當實際需要加入我的數據時,是否可以在存儲過程中返回多個結果集 – Xorandor

+0

我不確定我是否理解,是否需要多個結果集,在SP中是否有多個selectt語句。如果你需要加入然後加入。還是你想以一對多的方式將你創建的對象從結果集中鏈接到一起,就像使用外鍵的數據庫一樣? – gjvdkamp

+0

想要實現的更多示例代碼以及遇到的問題將對此有所幫助。 – gjvdkamp