0

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

SQL006
  • 439
  • 6
  • 21
  • 1
    I disagree with the vote to close because it is more than just splitting the string. Take a peek at https://dbfiddle.uk/oQmX9RUD – John Cappelletti Nov 01 '22 at 15:01
  • Thanks @JohnCappelletti for the solution. This is exactly what I want. Not sure how to accept your solution as answer as the post closed...I am trying to edit it to see if this post get reopened or not. – SQL006 Nov 01 '22 at 16:34
  • No worries. I could reopen, but let's just move on :) – John Cappelletti Nov 01 '22 at 16:39

0 Answers0