Last active
February 6, 2017 22:10
-
-
Save bertwagner/7268eb2687304b4b267bbd97435faca6 to your computer and use it in GitHub Desktop.
SQL Server 2016 JSON's JSON_QUERY() Function Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- See https://gist.github.com/bertwagner/356bf47732b9e35d2156daa943e049e9 for a formatted version of this JSON | |
DECLARE @garage nvarchar(1000) = N'{ "Cars": [{ "Make": "Volkswagen", "Model": { "Base": "Golf", "Trim": "GL" }, "Year": 2003, "PurchaseDate": "2006-10-05T00:00:00.000Z" }, { "Make": "Subaru", "Model": { "Base": "Impreza", "Trim": "Premium" }, "Year": 2016, "PurchaseDate": "2015-08-18T00:00:00.000Z" }] }' | |
-- This returns NULL because the values of Cars is an array instead of a simple object | |
SELECT JSON_VALUE(@garage, '$.Cars') | |
-- Output: NULL | |
-- Using JSON_QUERY() however returns the JSON string representation of our array object | |
SELECT JSON_QUERY(@garage, '$.Cars') | |
-- Output: [{ "Make": "Volkswagen", "Model": { "Base": "Golf", "Trim": "GL" }, "Year": 2003, "PurchaseDate": "2006-10-05T00:00:00.000Z" }, { "Make": "Subaru", "Model": { "Base": "Impreza", "Trim": "Premium" }, "Year": 2016, "PurchaseDate": "2015-08-18T00:00:00.000Z" }] | |
-- This instance of JSON_VALUE() correctly returns a singular scalar value | |
SELECT JSON_VALUE(@garage, '$.Cars[0].Make') | |
-- Output: Volkswagen | |
-- Using JSON_QUERY will not work for returning scalar values - it only will return JSON strings for complex objects | |
SELECT JSON_QUERY(@garage, '$.Cars[0].Make') | |
-- Output: NULL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment