I get the data in the below format in a table.
DROP TABLE IF EXISTS #Staging;
CREATE TABLE #Staging
(
Data varchar(max)
)
INSERT INTO #Staging
SELECT 'Column1,Column3,Column4,Column5'
UNION ALL
SELECT 'A,,C,D'
UNION ALL
SELECT 'A,,,'
UNION ALL
SELECT 'A1,4,5,6'
The data itself contains the column header in first row with delimiter ','. It is not mandatory to have all the columns or in correct order, in this example Column2 is missing so should be inserted as NULL in the destination table. The data need to loaded into below destination table.
CREATE TABLE #Final
(Column1 varchar(100),
Column2 varchar(100),
Column3 varchar(100),
Column4 varchar(100),
Column5 varchar(100)
)
The output should look like this
Column1 Column2 Column3 Column4 Column5
A NULL C D
A NULL
A1 NULL 4 5 6
Using the JSON split function https://www.mssqltips.com/sqlservertip/7034/sql-split-string-with-openjson/
I tried the below query to Pivot the data but it returning the first Row as I am just filtering the column names only.
SELECT
[Column1],[Column2],[Column3],[Column4],[Column5]
FROM(
SELECT Value FROM #Staging
CROSS APPLY dbo.SplitOrdered_JSON(Data, ',')
) As Src
PIVOT
(
MAX(Value)
FOR Value IN ([Column1],[Column2],[Column3],[Column4],[Column5])
)AS PivotTable
Please let me know how to get all the data. Thanks