Quantcast
Channel: SQL Server - How to transform JSON to Relational database - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Tim Mylott for SQL Server - How to transform JSON to Relational database

$
0
0

If SQL Version 2016+ use OPENJSON AND with_clause:

https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-2017

    DECLARE @JsonData NVARCHAR(MAX);    SET @JsonData = N'    {"table1": {"Name": "table1","Items": [          {"Id": 1,"FirstName": "John","LastName": "Wen","Country": "UK","PostCode": 1234,"Status": false,"Date": "2018-09-18T08:30:32.91"          },          {"Id": 2,"FirstName": "John1","LastName": "Wen1","Country": "UK1","PostCode": 12341,"Status": true,"Date": "2018-09-15T08:30:32.91"          }        ]      },"table2": {"Name": "table2","Items": [          {"Id": 1,"Name": "leo","StudentId": 102,"CreatedDate": "2018-09-18","Location": "USA"          }        ]      }    }';    --Table1    SELECT [a].[Id]         , [a].[FistName]         , [a].[Lastname]         , [a].[Country]         , [a].[PostCode]         , [a].[Status]         , [a].[Date]    FROM           OPENJSON(@JsonData, '$.table1.Items')               WITH (                        [Id] INT '$.Id'                      , [FistName] NVARCHAR(200) '$.FirstName'                      , [Lastname] NVARCHAR(200) '$.LastName'                      , [Country] NVARCHAR(200) '$.Country'                      , [PostCode] NVARCHAR(200) '$.PostCode'                      , [Status] NVARCHAR(200) '$.Status'                      , [Date] DATETIME '$.Date'                    ) [a];    --Table2    SELECT [a].[Id]         , [a].[Name]         , [a].[StudentId]         , [a].[CreatedDate]         , [a].[Location]    FROM           OPENJSON(@JsonData, '$.table2.Items')               WITH (                        [Id] INT '$.Id'                      , [Name] NVARCHAR(200) '$.Name'                      , [StudentId] INT '$.StudentId'                      , [CreatedDate] DATETIME '$.CreatedDate'                      , [Location] NVARCHAR(200) '$.Location'                    ) [a];

Viewing all articles
Browse latest Browse all 4

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>