2015-05-29 68 views
1

是否可以直接從MSSQL返回像這樣的數據結構?從存儲過程返回一列值作爲列表

public class MyClass 
{ 
     public int Id {get; set;} 
     public int List<int> AnotherIds {get; set;} 
} 

我需要這個檢索數據列出,如果編號是重複 例如: SELECT * FROM MyTable的

-------------------- 
| Id | AnthId | 
| 1  | 1 | 
| 1  | 2 | 
| 1  | 3 | 
| 2  | 1 | 
| 2  | 2 | 
| 2  | 3 | 
| 2  | 4 | 
-------------------- 

結果將是2個實體清單: MyClass的[0] { 1,[1,2,3]} MyClass [1] {2,[1,2,3,4]}

+0

是的。使用一個PIVOT – Dbloch

+0

必須知道你的數據庫結構來回答這個問題。包括你的模式。 –

+0

它可以更容易地使用ORM實體框架或返回數據表並在代碼中解析它。任何T-SQL解決方案都會強制你在代碼上做一些工作,因爲在sql中沒有List的概念。 –

回答

0

是的,這是可能的。我包括你可以複製/粘貼到您的查詢窗口爲例,使用這個例子建立你的SQL返回所需的數據:

declare @tbl table(ID int, AnotherID int) 
declare @aa varchar (200) 
declare @result table(ID int, AnotherIDs varchar(200)) 

set @aa = '' 

insert into @tbl (ID, AnotherID) Values(1,1) 
insert into @tbl (ID, AnotherID) Values(1,2) 
insert into @tbl (ID, AnotherID)Values(1,3) 
insert into @tbl (ID, AnotherID) Values(1,4) 

insert into @tbl (ID, AnotherID) Values(2,1) 
insert into @tbl (ID, AnotherID) Values(2,2) 
insert into @tbl (ID, AnotherID) Values(2,3) 
insert into @tbl (ID, AnotherID) Values(2,4) 

--select * from @tbl 


declare @i int 
select @i = min(ID) from @tbl 
declare @max int 
select @max = max(ID) from @tbl 

while @i <= @max begin 

select @aa = 
     coalesce (case when @aa = '' 
         then CAST(AnotherID as varchar) 
         else @aa + ',' + CAST(AnotherID as varchar) 
        end 
        ,'') 
     from @tbl where [email protected] 

insert into @result(ID, AnotherIDs) 
values(@i, @aa) 

     set @aa='' 

set @i = @i + 1 
end 

select * from @result 

結果是這樣的:
IDAnotherIDs
1 1,2,3,4
2 1,2,3,4

+0

以這種方式,我應該在c#中解析字符串,我不認爲,這是最好的解決方案,但謝謝 – lxmkv