1

我想将 SELECT 语句的结果输​​出为 JSON 对象。

id    name        active  Status
1     Bob Jones   1       Active
2     John Smith  0       Inactive

我需要这样的返回结果:

{"Active"  :[{"id":1,"name":"Bob Jones" ,"active":1}],
 "InActive":[{"id":2,"name":"John Smith","active":0}]}

如何使用查询?

我正在使用此代码

DECLARE @JSONTierDetails AS TABLE (TierDetails VARCHAR(8000))

INSERT INTO @JSONTierDetails 
    SELECT
        (SELECT id, name, active 
         FROM MyTable 
         WHERE Status = 'Active' 
         FOR JSON PATH, INCLUDE_NULL_VALUES) TierDetails

SELECT TierDetails 
FROM @JSONTierDetails

提前致谢

4

3 回答 3

0
-- Table definition
DECLARE @data TABLE(id int, [name] nvarchar(128), active bit, [status] nvarchar(30));

-- Insert test rows
INSERT @data VALUES(1, 'Bob Jones', 1, 'Active'), (2, 'John Smith', 0, 'Inactive');

-- Output
SELECT
    (SELECT id, name FROM @data WHERE active = 1 FOR JSON PATH) AS [Active],
    (SELECT id, name FROM @data WHERE active = 0 FOR JSON PATH) AS [Inactive]
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER;
于 2020-05-31T09:11:14.067 回答
0

您的案例需要数组包装器和每个 JSON 表达式的属性名称。添加数组包装器并不难,但属性名称是。, ROOT(<property_name>)afterFOR JSON PATH可能会被使用,但可能会以静态方式应用一次。

因此,可能首选动态查询,例如

DECLARE @JSONTierDetails NVARCHAR(MAX) = 
(
 SELECT 'SELECT ' + 
    STUFF((
            SELECT  N',(SELECT id, name, active 
                          FROM MyTable subT 
                         WHERE subT.status = ''' + status + N''' 
                           FOR JSON PATH
                       ) AS [' + status + N']' + CHAR(13) + '   '
              FROM MyTable t
            FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
        + 'FOR JSON PATH, WITHOUT_ARRAY_WRAPPER' );

EXEC (@JSONTierDetails);

Demo

于 2020-05-31T20:19:41.700 回答
-1

see this page in microsoft site: JSON Data (SQL Server)

于 2017-05-10T04:53:11.200 回答