Search
 
SCRIPT & CODE EXAMPLE
 

SQL

json object to column value in sql server

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 :: how to add amount between date in sql 
Sql :: query on date sqlite flutter 
Sql :: Should I use the datetime or timestamp data type in MySQL? 
Sql :: sql 
Sql :: doctors appointment 
Sql :: what is like operator in sql 
Sql :: postgres where 
Sql :: install sql server management studio ubuntu 
Sql :: sql selet 
Sql :: get last date join sql 
Sql :: ORA-06502: PL/SQL: numeric or value error: character string buffer too small 
Sql :: call rest api from postgresql 
Sql :: sql basic commands 
Sql :: convert sql to linq c# online 
Sql :: query params sql insert python f string 
Sql :: sql joins in python 
Sql :: swiftui onappear only once 
Sql :: SQL Using Comments to Debug Code 
Sql :: mysql group by derived column 
Sql :: oracle apex call duration 
Sql :: java input type sql date 
Sql :: select all column 
Sql :: how to see table associated with a schema in sql 
Sql :: sql not null constraint 
Sql :: horizontal join sqlite 
Sql :: mysql top percent 
Sql :: price-colour 
Sql :: subconjuntos da linguagem SQL 
Sql :: mysql beautifier terminla 
Sql :: which takes more space in a database a datetime or separate date and time columns? 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =