Laurent Kelly
Laurent Kelly

Reputation: 19

Splitting a column value (by ',') and creating a new table with column headers

I'm relatively new to SQL here. In SQL, I'm trying to convert an existing table into a new table where two columns are split into rows (by a comma ',').

Stack Overflow has recommended a similar solution here, however more complex as I don't require trimming/or replacing characters.

Original table

Row Index Question Titles Answers
0 Colour, Registration, Make, Model Red, A123456, Ford, Fiesta
1 Colour, Registration, Make, Model Blue, B23456, Audi, A3
2 Colour, Registration, Make, Model Purple, D52625, Nissan, Skyline
3 Colour, Registration, Make, Model Orange, Y336363, Toyota, Supra

Desired outcome

Row Index Question Titles Answers
0 Colour Red
0 Registration A123456
0 Make Ford
0 Model Fiesta
1 Colour Blue
1 Registration B23456
1 Make Audi
1 Model A3
2...etc Colour Purple

This is what I have so far, but I'm struggling to incorporate the 'Answers' side:

DECLARE @Get_Question_Titles VARCHAR(4000);
DECLARE @MaxID INT;
DECLARE @ThisID INT;

SET @Get_Question_Titles = (SELECT TOP 1 Question_Titles FROM Test_Car_Table)
--Get the max Row_Index (for the While loop)
SET @MaxID = (SELECT MAX(Row_Index) FROM Test_Car_Table)  
SET @ThisID = 0

DECLARE @Main_Table TABLE (ID INT, Title varchar(MAX), Answer varchar(MAX))

WHILE @ThisID <= @MaxID
BEGIN
    --Split the Get_Question_Titles up and insert into @Main_Table
    INSERT INTO @Main_Table
    SELECT @ThisID AS Row_Index, VALUE AS Question_Titles, NULL AS Answer
    FROM STRING_SPLIT(@Get_Question_Titles, ',')

    -- ADD VALUES TO COLUMN

    --Increment @ThisID
    SET @ThisID = @ThisID + 1
END

SELECT * FROM @Main_Table

This produces the following:

Row Index Question Titles Answers
0 Colour NULL
0 Registration NULL
0 Make NULL
0 Model NULL
1 Colour NULL
1 Registration NULL
1 Make NULL
1 Model NULL
2...etc Colour NULL

Does anybody know a way to produce the desired outcome?

Upvotes: -1

Views: 53

Answers (0)

Related Questions