2015-05-29 69 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