Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join json list with a table in SQL Server using OPENJSON?

I have json data which have a list of productDetails. I need to combine each of the detail with productId.

I am using a stored procedure. This is my code:

DECLARE @products AS TABLE(productName NVARCHAR(255), 
                           productId INT NOT NULL);

INSERT INTO @products  
    EXEC [saveproducts] @product;

From the above query, I will get the list of products as a table. Now I need to join the detail in the json with corresponding product

INSERT INTO @detail 
     SELECT
         [detaiId], [productId]
     FROM 
         OPENJSON(@detailJSON) 
     WITH(detailId UNIQUEIDENTIFIER 'strict $.detaiId',
       productId INT ??????);

How to get the productId by comparing the productName in @detailJSON and from table @products?

like image 702
S M Avatar asked Jan 02 '17 09:01

S M


Video Answer


1 Answers

Only a simple inner join is needed

 INSERT INTO @detail 
 SELECT
     J.[detaiId], P.[productId]
 FROM 
 @products P
 INNER JOIN
     OPENJSON(@detailJSON) 
 WITH(detailId UNIQUEIDENTIFIER 'strict $.detaiId',
      productName  NVARCHAR(255) 'strict $.productName'
   ) J 
 ON J.productName = P.productName 
like image 119
S M Avatar answered Sep 20 '22 20:09

S M