首页 > 解决方案 > MSSQL JSON 自动转 Go 结构

问题描述

我正在尝试使用 MSSQL JSON AUTO 轻松地从查询转到 Go Struct。返回的数据看起来 jsony,但在将其从字符串转换为我想要的已知结构时遇到了麻烦。

func main() {
    type LOBData struct {
        COB_ID  int     `json:"COB_ID"`
        GrossLoss   float64     `json:"GrossLoss"`
    }

    type ResultData struct {
        YearID  int     `json:"YearID"`
        EventID int     `json:"EventID"`
        Modelcode int   `json:"modelcode"`
        Industry float64    `json:"Industry"`
        LOB []LOBData       `json:"y"`
    }

    db, err := sql.Open("sqlserver", ConnString())
    checkErr(err)
    defer db.Close()

    var result string
    err = db.QueryRow(`
        SELECT i.YearID, i.EventID, i.modelcode, totalloss as Industry, y.COB_ID, y.GrossLoss
        FROM  dbo.CS_IndustryLossv8_7938 AS i INNER JOIN
        dbo.Tb_YLT AS y ON i.YearID = y.YearID AND i.EventID = y.EventID AND i.modelcode = y.Modelcode
        where YLT_DVID=25
        FOR JSON AUTO`).Scan(&result)

    fmt.Println(result)
    YLT:= ResultData{}
    //var YLT []ResultData
    err=json.Unmarshal([]byte(result), &YLT)
    checkErr(err)
    fmt.Println(YLT)
}

fmt.Printlin(result) 打印:

[{"YearID":7687,"EventID":101900,"modelcode":41,"Industry":1.176648913256758e+010,"y":[{"COB_ID":5,"GrossLoss":6.729697615695682e+003}]},.....

但 fmt.Println(YLT) 返回:

{0 0 0 0 []}

我收到“json 输入意外结束”的错误。

虽然 Go 没有字符串限制,但 MSSQL 有 8,000 个字符。如果我将查询限制在前 3 行并使用var YLT []ResultData它就可以了。无论如何使用 MSSQL 和 Go 来做这件事,还是我应该使用不同的服务器技术?

标签: sql-servergo

解决方案


道歉......找到了答案,与网格输出不同,MSSQL 将结果拆分为多行,而不是需要连接起来。

https://docs.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-ver15

FOR JSON 子句的输出 FOR JSON 子句的输出具有以下特征:

结果集包含单个列。

一个小的结果集可能包含一行。大型结果集将长 JSON 字符串拆分为多行。默认情况下,当输出设置为“结果到网格”时,SQL Server Management Studio (SSMS) 会将结果串联到一行中。SSMS 状态栏显示实际的行数。其他客户端应用程序可能需要代码通过连接多行的内容将冗长的结果重新组合成一个有效的 JSON 字符串。有关 C# 应用程序中此代码的示例,请参阅在 C# 客户端应用程序中使用 FOR JSON 输出。


推荐阅读