On SQL Server, I have an request generating a list of object in JSON format using FOR JSON PATH
. But I can't manage to handle the case where no rows are returned.
Create a table nammed mytable
:
CREATE TABLE [dbo].[mytable] (
[field_a] VARCHAR (50) NULL,
[field_b] VARCHAR (50) NULL,
[id] UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL,
CONSTRAINT [PK_mytable] PRIMARY KEY CLUSTERED ([id] ASC)
);
Database used: Microsoft SQL Azure (RTM) - 12.0.2000.8 May 12 2022 23:11:24 Copyright (C) 2022 Microsoft Corporation
SELECT
[mytable].[field_a] as [a],
[mytable].[field_b] as [b]
FROM
[mytable]
FOR JSON PATH, INCLUDE_NULL_VALUES
When rows are returned the request should return the following structure:
[]
The request as it's written return an empty result instead:
I have seen the WITHOUT_ARRAY_WRAPPER
option that I combined with CONCAT:
SELECT
CONCAT(
'[',
(
SELECT
[mytable].[field_a] as [a],
[mytable].[field_b] as [b]
FROM
[mytable]
FOR JSON PATH, INCLUDE_NULL_VALUES
),
']'
) as [jsonResult]
It's working in my case, but I think it's a bit ugly.
Is there a way to improve this request to display the array brackets whether there are rows or not?
The FOR JSON
operator does not return anything at all if there are no rows to serialize.
You can instead use ISNULL
to return an empty array
SELECT ISNULL((
SELECT
t.field_a as a,
t.field_b as b
FROM
mytable t
FOR JSON PATH, INCLUDE_NULL_VALUES
), '[]');