Search
 
SCRIPT & CODE EXAMPLE
 

SQL

Create table with JSON column 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 :: alter table drop partition hive 
Sql :: sql distinct vs unique 
Sql :: postgresql powershell query 
Sql :: if else sql 
Sql :: mysql filter by date mount 
Sql :: xampp mysql command to import a large database 
Sql :: how to find table lock and row lock in mysql 
Sql :: mysql select inside sum 
Sql :: how to check default value of column in sql server 
Sql :: get month sql 
Sql :: postgres stored procedure 
Sql :: what is unique key in sql 
Sql :: update join 
Sql :: frename oracle 
Sql :: download database devilbox 
Sql :: mysql workbench download 
Sql :: what is truncate in sql 
Sql :: case vhdl 
Sql :: psql command not found windows 
Sql :: select all from table left join 
Sql :: full-text index mysql 
Sql :: create user with encrypted password postgresql 
Sql :: mysql uuid 
Sql :: use of undefined constant mysql_assoc - assumed 
Sql :: SQL Server date literal 
Sql :: mysql create table 
Sql :: systems sql 
Sql :: how to select only a certain date sql 
Sql :: sql cross apply vs join 
Sql :: access refused mysql xampp server 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =