Search
 
SCRIPT & CODE EXAMPLE
 

SQL

SQL Server OPENJSON FROM table 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 :: double in sql server example 
Sql :: distinct in sql 
Sql :: sql unique 
Sql :: when matched in sql server 
Sql :: show specific events on mysql 
Sql :: control files oracle 
Sql :: sql 2 way of select unique 
Sql :: mysql order by on condition 
Sql :: how to start with sql 
Sql :: mysql query to select the highest value 
Sql :: convert negative to positive in sql 
Sql :: unique key in sql 
Sql :: mysql workbench format date 
Sql :: SQL Server Splitting a string column into multiple rows, while repeating ID column 
Sql :: sql trying to delete database in use 
Sql :: time in sql server 
Sql :: copy data from one postgres container to another 
Sql :: python sqlalchemy orm to select null values 
Sql :: sqlite löschen einer tabelle 
Sql :: sql cte example 
Sql :: create fulltext index mysql 
Sql :: rename temp table column name in sql server 
Sql :: get string between specific character sql 
Sql :: oracle convert hours to minutes 
Sql :: not equal in mysql query 
Sql :: select all columns except one sql 
Sql :: Oracle cx_Oracle example 
Sql :: how to install mssql on mac 
Sql :: select query in sql 
Sql :: postgresql connect 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =