I'm using SQL Server 2014 and aware that out of the box it does not support JSON.
We are receiving data from a 3rd party supplier that will look like the below:
{
"PersonID": "1",
"MarketingPreference": "Allow",
"AllowPhone": "No",
"AllowEmail": "Yes",
"AllowTxt": "Yes",
"AllowMob": "Yes"
}
However, we may sometimes also receive the below:
{
"PersonID": "2",
"MarketingPreference": "DoNotAllow"
}
I need to insert these values into a table - what is the best way to do this if SQL Server 2014 does not support JSON?
If I convert the JSON to XML it looks like the below:
<PersonID>1</PersonID>
<MarketingPreference>Allow</MarketingPreference>
<AllowPhone>No</AllowPhone>
<AllowEmail>Yes</AllowEmail>
<AllowTxt>Yes</AllowTxt>
<AllowMob>Yes</AllowMob>
How do I then extract the values from the XML?
DECLARE @xml XML
SET @xml = N'
<PersonID>1</PersonID>
<MarketingPreference>Allow</MarketingPreference>
<AllowPhone>No</AllowPhone>
<AllowEmail>Yes</AllowEmail>
<AllowTxt>Yes</AllowTxt>
<AllowMob>Yes</AllowMob>'
SELECT
Tab.Col.value('@PersonID','int') AS ContactID,
Tab.Col.value('@MarketingPreference','varchar(20)') AS Pref,
Tab.Col.value('@AllowPhone','varchar(20)') AS Phone,
Tab.Col.value('@AllowEmail','varchar(20)') AS Email,
Tab.Col.value('@AllowTxt','varchar(20)') AS Txt,
Tab.Col.value('@AllowMob','varchar(20)') AS Mob
FROM
@xml.nodes('/root/') Tab(Col)
GO;
But now I get this error:
Incorrect syntax near 'GO'.
Is there an easier way to select the values from JSON?
GO
isn't a T-SQL operator; it doesn't require termination. The;
goes after your T-SQL statements;...lowMob>';
and...Tab(Col);
GO
isn't a SQL statement but a batch separator; it must never be followed by a;
. Your XML approach would be decent if your XML was valid, but it's not (you need to wrap what you've got inside an actual root element, e.g.<root>...</root>
). Last but not least, your query syntax is querying for attributes rather than elements (PersonID[1]
, not@PersonID
) andnodes
should use/root
, not/root/
. Fix all that and Bob's your uncle.OPENJSON()
out of the box