Home >Database >Mysql Tutorial >How to Output SELECT Query Results as JSON Using SQL Server Functions?

How to Output SELECT Query Results as JSON Using SQL Server Functions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 03:29:10778browse

How to Output SELECT Query Results as JSON Using SQL Server Functions?

Output SELECT Results as JSON Using SQL Server Functions

Query:

To output the results of a SELECT statement as a JSON object using a function, you can utilize the following approach:

FOR JSON AUTO (SQL Server 2016 ):

SELECT id, name, active
FROM Users
FOR JSON AUTO;

FOR XML PATH (SQL Server Pre-2016):

SELECT '[' + STUFF((
    SELECT
        ',{"id":' + CAST(id AS VARCHAR(MAX))
        + ',"name":"' + name + '"'
        + ',"active":' + CAST(active AS VARCHAR(MAX))
        + '}'
    FROM Users t1
    FOR XML PATH(''), TYPE
).VALUE('.', 'VARCHAR(MAX)'), 1, 1, '') + ']';

Example:

Consider the following "Users" table:

id name active
1 Bob Jones 1
2 John Smith 0

The above queries would return the following JSON result:

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

The above is the detailed content of How to Output SELECT Query Results as JSON Using SQL Server Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn