0

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.

DDL and sample data population

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

The request

SELECT
 [mytable].[field_a] as [a],
 [mytable].[field_b] as [b]
FROM
 [mytable]
FOR JSON PATH, INCLUDE_NULL_VALUES

Expectation when no rows are returned

When rows are returned the request should return the following structure:

[]

Reality when no rows are returned

The request as it's written return an empty result instead:

An ugly solution

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?

2
  • While asking a question, you need to provide a minimal reproducible example: (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in the #1 above. (4) Your SQL Server version (SELECT @@version;). Commented Aug 11, 2022 at 15:11
  • thanks for your reply @YitzhakKhabinsky , i've added a table creation script for reproduction purposes. Commented Aug 11, 2022 at 15:23

1 Answer 1

1

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
  ), '[]');

db<>fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.