Search
 
SCRIPT & CODE EXAMPLE
 

SQL

Split JSON data in SQL Server column

DROP TABLE IF EXISTS #TempDestinationTable 
DROP TABLE IF EXISTS ##TempResultTable

DECLARE @cols AS NVARCHAR(MAX) = ''      
,@query  AS NVARCHAR(MAX);  

DECLARE @TabRecord NVARCHAR(100)='{"firstName":"Bill","lastName":"Gates","skills":["C#","SQL"]}'

SELECT [key] AS ColumnName      
,value       
INTO #TempDestinationTable      
FROM OPENJSON(@TabRecord);  

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[ColumnName])       
	FROM #TempDestinationTable c      
	FOR XML PATH(''), TYPE      
	).value('.', 'NVARCHAR(MAX)')       
,1,1,'')  


DECLARE @TableProperty NVARCHAR(MAX)=  REPLACE(@cols, ',', ' NVARCHAR(MAX),')      
SET @TableProperty  = @TableProperty+' NVARCHAR(MAX)'      
DECLARE @TableQuery NVARCHAR(MAX)= 'CREATE TABLE ##TempResultTable ('+@TableProperty+')'      
EXEC(@TableQuery) 

set @query = 'SELECT ' + @cols + ' from       
    (      
     select value, ColumnName      
     from #TempDestinationTable      
      ) x      
    pivot       
    (      
     max(value)      
     for ColumnName in (' + @cols + N')              
    ) p '      
      
 INSERT INTO ##TempResultTable      
 execute(@query)  
 
SELECT * FROM ##TempResultTable

DROP TABLE IF EXISTS #TempDestinationTable
DROP TABLE IF EXISTS ##TempResultTable
Comment

PREVIOUS NEXT
Code Example
Sql :: mysql nested query 
Sql :: double in sql server example 
Sql :: sql select 
Sql :: update row postgres 
Sql :: sql server set default value equal to auto increment 
Sql :: sql get month 
Sql :: SQL Primary Key multiple column 
Sql :: how to generate ids in sql 
Sql :: primary key sql 
Sql :: mysql trigger 
Sql :: mysql count 
Sql :: missing left parenthesis error in sql 
Sql :: SQL Syntax of INNER JOIN 
Sql :: sql server find all referencing objects to user-defined table type 
Sql :: left join in sql oracle 
Sql :: oracle compile trigger 
Sql :: how to rename column name in sql server using query 
Sql :: SQL Server modify_timestamp trigger 
Sql :: mysql range of dates overlap 
Sql :: mysql order by rand limit 1 really slow 
Sql :: mysql update multiple columns 
Sql :: offset in postgresql example 
Sql :: sql order by except one row 
Sql :: linux upload database to mysql 
Sql :: import sql file to mysql db using shell commands 
Sql :: update sql 
Sql :: above average salary in sql 
Sql :: mysql sleep connections 
Sql :: equi joins in oracle 
Sql :: join multiple tables in sql 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =