Reputation: 321
Hello I need to write a JSON into a SQL column during a insert in a stored procedure.
Something like:
INSERT INTO TableA (ColumnA)
SELECT
'{"PropertyA":' + '"' + valueA + '"' + ',"PropertyB":' + '"' + valueB + '"}
FROM TableB
The above works, and it inserts the following: {"PropertyA:""SomeValue","PropertyB:""AnotherValue"}
But I'm hoping to format the statement into something more legible using SQL Functions if they exist.
Upvotes: 0
Views: 35
Reputation: 49
Sounds like you are looking for FROM OPENJSON(<jsonstring>)
See this example from the documentation
DECLARE @json NVARCHAR(MAX);
SET @json = N'[
{"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
{"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';
SELECT *
FROM OPENJSON(@json)
WITH (
id INT 'strict $.id',
firstName NVARCHAR(50) '$.info.name',
lastName NVARCHAR(50) '$.info.surname',
age INT,
dateOfBirth DATETIME2 '$.dob'
);
Upvotes: 1