【问题标题】:Return one column values as list from stored procedure从存储过程中返回一列值作为列表
【发布时间】:2015-08-12 08:35:20
【问题描述】:

是否可以直接从 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 个实体的列表: 我的班级[0]{1, [1,2,3]} 我的类[1]{2, [1,2,3,4]}

【问题讨论】:

  • 是的。使用 PIVOT
  • 必须知道你的数据库结构才能回答这个问题。包括您的架构。
  • 使用类似 ORM 的实体框架或返回数据表并在代码中解析它会更容易。无论如何,任何 T-SQL 解决方案都会迫使您在代码上做一些工作,因为 sql 中没有 List 的概念。

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


【解决方案1】:

是的,这是可能的。我提供了一个示例,您可以将其复制/粘贴到您的查询窗口中,并使用此示例构建您的 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

【讨论】:

  • 这样我应该用c#解析字符串,我不认为这是最好的解决方案,但是谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
相关资源
最近更新 更多