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

Querying Json array column and other current table column

I have a table that has three columns from which I need to retrieve the data. One of the columns OtherNames contain an array of Json Objects.

CREATE TABLE Persons (
    NameID int,
    CurrentName varchar(255),
    OtherNames varchar(max),
);

I can query that column just fine, but how can I join it with the table it is in by ID so I can retrieve all the information on the table and what is related to this row.

DECLARE @test VARCHAR(MAX)

SELECT @test = '[{"Name":"Bob","DateTime":"03/03/2022"},{"Name":"Adam","DateTime":"04/05/2022"}]'

SELECT * FROM OPENJSON(@test)
    WITH (
    Name VARCHAR(MAX) '$.Name',
    DateTime VARCHAR(MAX) '$.DateTime' 
    )

This above results in

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

Bob     03/03/2022 
Adam    04/05/2022 

How can I join to show the NameID and CurrentName along with it ?

NameID   Name      DateTime    CurrentName
1        Bob         03/03/2022  Rob
1        Adam        04/05/2022  Rob

There could be multiple records and multiple Json data..

>Solution :

As I mentioned in the comments, use OPENJSON against the column, not a scalar variable which contains the value of just one of your rows, and none of the other row data.

SELECT P.NameID,
       ONs.[Name],
       ONs.[DateTime],
       P.CurrentName
FROM dbo.Persons P
     CROSS APPLY OPENJSON(P.OtherNames)
                 WITH ([Name] varchar(255),
                       [DateTime] date) ONs;

Note that as your value [DateTime] is culture dependant, you may need to define it as a varchar(10) in the WITH, and then CONVERT it to a date in the SELECT with a style code.

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