Search
 
SCRIPT & CODE EXAMPLE
 

SQL

json to dynamic columns in sql

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 :: sql distinct vs unique 
Sql :: sql cheat sheet 
Sql :: date less than in sql 
Sql :: sql server set default value equal to auto increment 
Sql :: sql left join with where clause 
Sql :: between date in sql server 
Sql :: mysql update 
Sql :: how to create triggers in sql server 
Sql :: select only unique values from and to current table 
Sql :: wamp server mysql password 
Sql :: sql server delete records with specific date 
Sql :: mysql string split to array 
Sql :: changing column names in sql query results 
Sql :: t-sql never ending delete 
Sql :: como hacer un select entre fechas mysql 
Sql :: check if table is Temporal 
Sql :: mysql grouping functions 
Sql :: stored procedure data to table 
Sql :: postgres between dates 
Sql :: selecting specific day in colum sql 
Sql :: sql not in operator 
Sql :: oracle datafile max size 32gb 
Sql :: postgres insert timestamp without timezone 
Sql :: psql store procedure-return multiple table values 
Sql :: mariadb used space 
Sql :: postgresql select top 1 from each group 
Sql :: cte in sql server 
Sql :: oracle swap partition 
Sql :: get first match in each group mysql query 
Sql :: Concatenate columns in table 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =