Published on

January 8, 2017

Exploring JSON in SQL Server

Learning new things can be an amazing experience, just like watching a child explore a new toy. In the world of SQL Server, the introduction of JSON in SQL Server 2016 has opened up a whole new realm of possibilities. Let’s dive into the concept of JSON and its potential value.

JSON, or JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is widely used for transmitting data between a server and a web application, as an alternative to XML.

In SQL Server, you can work with JSON data using various functions and operators. Let’s take a look at a simple code example:

DECLARE @myjson NVARCHAR(MAX) =
'{
	"Name": "Pinal",
	"Surname": "Kumar",
	"Birth": {"DOB":"2000-12-12" , "Town":"Gandhi Nagar", "Country":"India"}
}'

SELECT JSON_VALUE(@myjson, '$.Name') 

In the above code, we declare a variable called @myjson and assign it a JSON string. We then use the JSON_VALUE function to retrieve the value of the “Name” property from the JSON string. In this case, the output would be “Pinal”.

However, it’s important to note that working with JSON in SQL Server requires attention to detail. Even a simple mistake, such as using a different case or trying to retrieve a non-existing property, can result in a NULL output. For example:

SELECT JSON_VALUE(@myjson, '$.name')
SELECT JSON_VALUE(@myjson, '$.name123')

In the above example, both statements will return NULL, as the properties “name” and “name123” do not exist in the JSON string.

So, how can we handle such scenarios and identify whether it was an invalid property or a case-sensitive problem? One approach is to use the ISNULL function to check if the JSON_VALUE function returns NULL, and then provide a default value or handle the error accordingly.

For example:

SELECT ISNULL(JSON_VALUE(@myjson, '$.Name'), 'Property not found') AS Name

In this case, if the “Name” property is not found, the output will be “Property not found” instead of NULL.

Exploring JSON in SQL Server can be a fascinating journey, filled with new discoveries and challenges. As you start working with JSON, I encourage you to share your experiences and solutions in the comments below. Let’s continue to learn and grow together!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.