0

My sample code is like this:

DECLARE @JsonText varchar(MAX) = '{
    "Test": ""
}'

DECLARE @Name varchar(MAX) = JSON_VALUE(@JsonText, '$.Test') ;

IF (@Name IS NULL)
BEGIN
    SELECT 'Null' AS Result
END
ELSE
BEGIN 
    SELECT 'Empty' AS Result
END

and I got an output:

Result
----------
Empty

My expected output is Null, I have tried with trim and then check string is empty then return null is working fine.

IF (@Result = '') 
    SET @Result = NULL; 

But I am looking for any other alternative if available which returns null instead of empty.

2
  • 1
    If you want the value to be NULL, then define the value as Null in your JSON. Null and "" are not the same value, just like NULL and '' aren't. Commented Nov 25, 2021 at 20:55
  • Can you explain why you want NULL? NULL signifies unknown but it's not unknown - it's and empty string. Commented Nov 25, 2021 at 21:01

1 Answer 1

4

A zero length string (in JSON "" and in T-SQL '') and NULL are not the same value. In your JSON you have a zero length string. If you want a NULL value to be returned from your JSON then define the value as Null in your JSON:

DECLARE @JsonText nvarchar(MAX) = N'{
    "Test": null
}';

DECLARE @Name nvarchar(MAX) = JSON_VALUE(@JsonText, '$.Test');
IF (@Name IS NULL)
BEGIN
    SELECT 'Null' AS Result;
END
ELSE
BEGIN 
    SELECT 'Empty' AS Result;
END;

This returns the varchar value 'Null'.

Alternatively, you could use NULLIF to return NULL if your expression returns a zero length string, but I would suggest that really it's the JSON that needs correcting:

SET @Name = NULLIF(JSON_VALUE(@JsonText, '$.Test'),N'');
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.