This is tagged with [sql-server-2012]
- what a pity... With v2016+ you could call for STRING_SPLIT
or even JSON methods... The following is a rather hacky approach but works - at least with your provided test data...
Create a mockup-table (please do this yourself the next time).
DECLARE @tbl TABLE(ID INT IDENTITY, YourString VARCHAR(100));
INSERT INTO @tbl VALUES
('["2","3","4"]')
,('["1","2","3"]')
,('[]')
,('["Select option B","Select option C","Select option D"]')
,('["Moderate","Heavy","Heavy, Big & Abnormal"]');
--This is the query:
SELECT t.ID
--,t.YourString
,C.Separated.value('text()[1]','nvarchar(max)') AS Parted
FROM @tbl t
CROSS APPLY(SELECT REPLACE(REPLACE(REPLACE(YourString,'"','"'),'["',''),'"]','')) A(replaced)
CROSS APPLY(SELECT CAST('<x>' + REPLACE((SELECT A.replaced [*] FOR XML PATH('')),'","','</x><x>') + '</x>' AS XML)) B(casted)
CROSS APPLY B.casted.nodes('/x') C(Separated);
The idea in short:
First of all I use multiple REPLACE()
to clean and harmonise your data. The second CROSS APPLY
will then use XML to split up your strings by replacing each comma together with the quotes! with XML tags. Thus we can prevent splitting at internal commas. But before, we have to use FOR XML
on the orginal string, to allow characters such as the &
in Big & Abnormal
. The rest ist rather easy XPath/XQuery
.
The result
+----+-----------------------+
| ID | Parted |
+----+-----------------------+
| 1 | 2 |
+----+-----------------------+
| 1 | 3 |
+----+-----------------------+
| 1 | 4 |
+----+-----------------------+
| 2 | 1 |
+----+-----------------------+
| 2 | 2 |
+----+-----------------------+
| 2 | 3 |
+----+-----------------------+
| 3 | [] |
+----+-----------------------+
| 4 | Select option B |
+----+-----------------------+
| 4 | Select option C |
+----+-----------------------+
| 4 | Select option D |
+----+-----------------------+
| 5 | Moderate |
+----+-----------------------+
| 5 | Heavy |
+----+-----------------------+
| 5 | Heavy, Big & Abnormal |
+----+-----------------------+