【问题标题】:How to get a nested list in sql server如何在sql server中获取嵌套列表
【发布时间】:2021-08-31 00:29:55
【问题描述】:

我正在尝试使用嵌套列表获取结果列表。 我需要 fileds[3] 来拥有所有 Symbol 类的字段。

我的 C# 模型是:

public class Watchlist
{
    public Watchlist(object[] fields)
    {
        WatchlistId = (int)fields[0];
        AccountId = (string)fields[1];
        Name = (string)fields[2];
        SymbolList = SetSymbolData(fields[3]);
    }

    public int WatchlistId { get; set; }
    public string AccountId { get; set; }
    public string Name { get; set; }
    public List<Symbol> SymbolList { get; set; }
}

public class Symbol
{
    public Symbol() { }

    public Symbol(object[] fields)
    {
        Ticker = fields[0] == null ? "" : fields[0].ToString();
        Exchange = fields[1] == null ? "" : fields[1].ToString();
        Name = fields[2] == null ? "" : fields[2].ToString();
    }

    public string Ticker { get; set; }
    public string Name { get; set; }
    public string Exchange { get; set; }
}

我当前的 SQL 是这样的:

SELECT w.Id, w.Account_id, w.Name, s.symbol, s.name, s.exchange FROM
(SELECT Id, Account_id, Name FROM Watchlists where Account_id = @AccountId) w
JOIN WatchlistSymbols ws ON w.Id = ws.WatchlistId
JOIN Symbols s ON s.id = ws.SymbolId

结果:

Id   Account_id    Name  symbol   name            exchange
----------- -----------------------------------------------------
26     123         TEST   AAA     Listed Funds     PACF
26     123         TEST  ACQRU    Independence     NQSC
26     123         TEST   ACTD    ArcLight         NQSC

但这会为每个关注列表符号组合返回一行。

【问题讨论】:

  • 您需要提供样本数据和所需的输出

标签: c# sql sql-server


【解决方案1】:

来自 SQL 数据库的结果集始终是每行具有固定列数的表,不能直接从 SQL 中获得“锯齿状”或“嵌套”结果作为结果集。

你有三个选择。

一个是change SQL Server's output to JSON 并使用类似 Newtonsoft nuget 包的东西解析该 json。

另一个是读取结果集并在 C# 中编写自己的嵌套循环来处理行。

第三种方法是使用对象关系映射器,并告诉它如何解析表格结果集。 Here's an example solution using Dapper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 2013-11-13
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多