从存储过程返回一列值作为列表

时间:2015-05-29 12:55:50

标签: c# sql-server stored-procedures return-value

是否可以直接从MSSQL返回这样的数据结构?

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

如果Id是重复的,我需要这个来检索要列出的数据 例如: 选择* 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]}

1 个答案:

答案 0 :(得分: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 ID=@i

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

        set @aa=''

set @i = @i + 1
end

select * from @result

结果如下:
ID AnotherIDs
1 1,2,3,4
2 1,2,3,4