Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a JSON object to be sent as parameter to Stored Procedure

I have a stored proc say sp_proc_1 which takes in a few parameters say @val1, @val2, and @val3. I would like to make a JSON object using the values @val1 and @val2 so that I can pass that JSON object as one of the parameters to a second stored procedure sp_proc2 which I will be invoking from sp_proc1. Please guide.

The way I think is to insert @val1 and @val2 into a temp_table and then select them from the temp_table into a JSON object. Am I thinking right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The statement depends on the format of the expected JSON output, but a possible option is FOR JSON PATH:

CREATE PROCEDURE Proc_1
   @val1 int,
   @val2 varchar(100),
   @val3 datetime
AS
BEGIN
   DECLARE @json nvarchar(max)
   SET @json = (SELECT @val1 AS val1, @val2 AS val2 FOR JSON PATH)
   
   EXEC Proc_2 @json
END   

The generated JSON is:

[{"val1":1,"val2":"Test value"}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading