【问题标题】:Re-use T-SQL FOR JSON subquery重用 T-SQL FOR JSON 子查询
【发布时间】:2019-12-14 16:03:57
【问题描述】:

这是一个嵌套 FOR JSON 查询的简单示例:

select 
    u.Id,
    u.Name,
    (select ue.Email
     from UserEmails ue
     where ue.UserId = u.Id
     for json path
    )
from
    Users u
for json path

有没有办法重用UserEmails 子查询?例如在一个函数中?

喜欢:

select 
    u.Id,
    u.Name,
    u.Email,
    dbo.GetUserEmailsJSON(u.Id)
from
    Users u
for json path

我还希望能够自行调用dbo.GetUserEmailsJSON() 并以 JSON 格式返回数据。

【问题讨论】:

    标签: sql json for-json


    【解决方案1】:

    我想通了......以下作品

    功能:

    create function GetUserEmailsJSON
    (
        @UserId int
    )
    returns nvarchar(max)
    as
    begin
        declare @result nvarchar(max)
        set @result = (
            select *
            from UserEmails ue
            where ue.UserId = @UserId
            for json path, include_null_values
        )
    
        return @result;
    end
    

    然后您的查询将如下所示:

    SELECT u.*
          ,json_query(dbo.GetUserEmailsJSON(u.Id)) 'Emails'
      FROM Users u
      for json path, include_null_values
    

    我唯一不喜欢的是将标量值函数调用为子查询 - 这可能非常费力。有人有其他建议吗?

    现在我需要弄清楚如何从 EF Core 调用这个函数并将 JSON 返回到一个对象中......有什么建议吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多