SQL Server Read JSON column from SQL Table and concat JSON array into string [duplicate]

bvk5enib  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

This question already has answers here:

Deconstructing JSON array within a JSON SQL Server (2 answers)
How to use OPENJSON to concatenate json Array in a column of a table (1 answer)

How to concatenate text from multiple rows into a single text string in SQL Server (48 answers)
Closed 8 days ago.

I'm trying to read data from a table who has multiple columns and one of them is JSON data. Inside this JSON there is an array of JSON's that I want to get one specific value.

The JSON looks like this:

{
    "FirstName": "Carlos",
    "LastName": "Perez",
    "PhoneNumbers": [{
        "PhoneNumber": "123456789"
    },
    {
        "PhoneNumber": "987654321"
    }]
}

What I want is to read this JSON column so it gives me only the phones numbers.

I want to get a result like this:
| Id | Column 1 | Column 2 | JSON Column |
| ------------ | ------------ | ------------ | ------------ |
| 1 | Value 1 | Value 2 | 123456789, 987654321 |

b4lqfgs4

b4lqfgs41#

Your question can be improved by including a snippet of what you've done/tried and perhaps the challenge with that you can get tailored help with context, in any case, here's a SQL query to achieve your desired result.

SELECT
    Id,
    Column1,
    Column2,
    JSON_QUERY(YourJSONColumn, '$.PhoneNumbers[*].PhoneNumber') AS PhoneNumbers,
    STUFF((
        SELECT ', ' + PhoneNumber
        FROM OPENJSON(YourJSONColumn, '$.PhoneNumbers')
        WITH (PhoneNumber NVARCHAR(255) '$.PhoneNumber')
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS ConcatenatedPhoneNumbers
FROM YourTable;

Remember to replace YourTable with the actual name of your table and YourJSONColumn with the name of your JSON column

Edit: Optimising the query

SELECT
    Id,
    Column1,
    Column2,
    JSON_QUERY(YourJSONColumn, '$.PhoneNumbers') AS PhoneNumbers,
    STRING_AGG(JSON_VALUE(phoneNumber.value, '$.PhoneNumber'), ', ') AS ConcatenatedPhoneNumbers
FROM YourTable
CROSS APPLY OPENJSON(YourJSONColumn, '$.PhoneNumbers') 
    WITH (PhoneNumber NVARCHAR(255) '$.PhoneNumber') AS phoneNumber
GROUP BY Id, Column1, Column2, YourJSONColumn;

相关问题