t-sql для json пропустить имена столбцов в результате - PullRequest
0 голосов
/ 31 мая 2018

У меня есть следующий запрос t-sql, который возвращает json:

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?

1 Ответ

0 голосов
/ 31 мая 2018

В основном вы хотите сгенерировать динамический json, поэтому вы можете попробовать использовать динамический TSQL, используя преимущества новой функции SQL Server 2017 STRING_AGG (дополнительная информация здесь ):

--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  

Результаты:

enter image description here

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