0

:두 개의 열을 키 - 값 json 객체로 변환 하시겠습니까? (제품의 속성을 나타내는)는 다음 레코드 세트에 <code>FOR JSON AUTO</code> 또는 <code>FOR JSON PATH</code>을 사용

attribute | value 
----------------- 
color  | red 
size  | small 

가 생성됩니다

[{"attribute":"color","value":"red"},{"attribute":"size","value":"small"}] 

다음 대신 생성 할 수있는 방법이 있나요 :

{"color":"red","size":"small"} 

참고 모든 제품 속성 다른 것보다 다르다. 그래서이 레코드 세트는 모든 제품마다 다릅니다. PIVOTing은 동적 SQL을 필요로하므로 옵션이 아닙니다! 예를 들어 제품 카탈로그을 생성하기 위해 제품 테이블과 함께 CROSS 수있는 기능이 필요합니다. "빨간색": 스크립트 다음에서 볼 수 있듯이 대신 SQL 서버 2016의 JSON 기능

답변

2

, 나는 두 제품 항목에 대해 다음과 같이

/*create table ProductAttributes (
    product int, 
    attribute varchar(40), 
    value varchar(40) 
) 
insert into ProductAttributes select 1, 'color', 'red' 
insert into ProductAttributes select 1, 'size', 'small' 
insert into ProductAttributes select 2, 'processor', 'intel' 
insert into ProductAttributes select 2, 'ram', '16' 
insert into ProductAttributes select 2, 'weight', '2'*/ 

select 
    product, '{' + STRING_AGG('"' + attribute + '":"' + value + '"' ,',') + '}' as attributes 
from ProductAttributes 
group by product 

출력이 제품 1 { "컬러"를 속성입니다 string concatenation function string_agg in SQL Server 2017 사용 "크기": "작은"} 2 { "프로세서": "인텔", "램": "16", "무게": "2"}

enter image description here

당신은을 사용하는 경우 이전 버전

SELECT 
    product, 
    '{' + STUFF(
    (
    SELECT 
     ',' + '"' + attribute + '":"' + value + '"' 
    FROM ProductAttributes a 
     where a.product = p.product 
    FOR XML PATH(''),TYPE 
    ).value('.','VARCHAR(MAX)' 
    ), 1, 1, '' 
) + '}' As attributes 
from ProductAttributes p 
group by product 

개발자를 다음과 같이 SQL 서버 2017보다, 당신은 동일한 결과

enter image description here

+0

달콤한 물건을 얻을 것이다 string concatenation using SQL XML Path을 사용할 수 있습니다! Microsoft가 독점적 인 기능을 추가 할 때까지 좋은 해결 방법을 제시합니다. Tanx. – dNitro