【问题标题】:t-sql for json skip column names in a result用于 json 的 t-sql 在结果中跳过列名
【发布时间】:2018-05-31 08:17:47
【问题描述】:

我有以下返回 json 的 t-sql 查询:

SELECT
    CF.Name
  , UCF.Value
FROM dbo.ClaimsCustomFields CF
LEFT JOIN dbo.UserCustomFields UCF
       ON UCF.FieldId = CF.Id
WHERE CF.CustomerId = 2653
FOR JSON PATH;

接下来是这个查询的输出:

    [  
   {  
      "Name":"zipCode",
      "Value":"zip zip zipC  zipCod"
   },
   {  
      "Name":"time111zone",
      "Value":"UTC +2"
   },
   {  
      "Name":"tttt",
      "Value":"Company organization tessss"
   }
]

但我想得到以下格式的结果:

   [  
   {  
      "zipCode":"zip zip zipC  zipCod"
   },
   {  
      "time111zone":"UTC +2"
   },
   {  
      "tttt":"Company organization tessss"
   }
]

是否可以使用FOR JSON 语句来实现这一点?

【问题讨论】:

  • 哪个 sql server 版本?
  • @B3S sql-server 2017

标签: json sql-server tsql sql-server-2017


【解决方案1】:

你基本上是想生成一个动态的 json,所以你可以尝试使用动态 TSQL,利用 SQL Server 2017 的新功能STRING_AGG(更多信息here):

--this table contains your sample data
declare @tmp table([Name] varchar(50),[Value] varchar(50))
--this variable will contain the dynamic tsql command 
declare @sql nvarchar(max)

--this temp table will hold the dynamically generated json fragments
if object_id('#tmp') is null
    create table #tmp (js varchar(max))

--fill table with test data 
insert into @tmp values
    ('zipCode'     ,'zip zip zipC  zipCod'),
    ('time111zone' ,'UTC +2'),
    ('tttt'        ,'Company organization tessss')

--generate a TSQL command that inserts each single JSON fragment into a temp table
select @sql = string_agg('insert into #tmp(js) values((select ''' + [Value] +''' as ''' 
              + [Name]+'''  for json path , WITHOUT_ARRAY_WRAPPER))', ';') 
from @tmp

--execute the dynamic TSQL command that fills the temp table with JSON fragments
exec(@sql)

--concatenate all the JSON fragments adding square brackets
select '[' + string_agg(js,',') + ']' as result from #tmp  

结果:

[{"zipCode":"zip zip zipC  zipCod"},{"time111zone":"UTC +2"},{"tttt":"Company organization tessss"}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多