Table name: D_order
OrderID OrderName
11,12 A:B
13,14 C:D
Output required
OrderID OrderName
11 A
12 B
13 C
14 D
Table name: D_order
OrderID OrderName
11,12 A:B
13,14 C:D
Output required
OrderID OrderName
11 A
12 B
13 C
14 D
Recursive function might help
check this Answer https://stackoverflow.com/a/5493616/6631280
or Check this fiddle http://sqlfiddle.com/#!18/f54fd/10
;WITH tmp(OrderID, OrderName, String) AS
(
SELECT
OrderID,
OrderName,
LEFT(String, CHARINDEX(',', String + ',') - 1),
STUFF(String, 1, CHARINDEX(',', String + ','), '')
FROM Testdata
UNION all
SELECT
OrderID,
OrderName,
LEFT(String, CHARINDEX(',', String + ',') - 1),
STUFF(String, 1, CHARINDEX(',', String + ','), '')
FROM tmp
WHERE
String > ''
)
SELECT
OrderID,
OrderName,
FROM tmp
ORDER BY OrderID
You should split the strings and make union. I used approach for spliting string described here.
The code:
SELECT substring(OrderId, 1, CHARINDEX(',',OrderId)-1) OrderId,
substring(OrderName, 1, CHARINDEX(':',OrderName)-1) OrderName
FROM YourDataTable
UNION ALL
SELECT substring(OrderId, CHARINDEX(',',OrderId)+1, LEN(OrderId)),
substring(OrderName, CHARINDEX(':',OrderName)+1, LEN(OrderName))
FROM YourDataTable
This works only for the formatting in the sample data.
If you have SQL Server 2016+, you may try an approach, based on JSON. Just transform the data into valid JSON arrays and parse these arrays with OPENJSON()
. The result is a table with columns key
, value
and type
, and the key
column holds the index of the element in these arrays. With this approach you can parse more than two elements.
Table:
CREATE TABLE Data (
OrderID nvarchar(100),
OrderName nvarchar(100)
)
INSERT INTO Data
(OrderID, OrderName)
VALUES
('11,12', 'A:B'),
('13,14', 'C:D'),
('15,16,17,18', 'E:F:G:H')
Statement:
SELECT j1.[value] AS OrderId, j2.[value] AS OrderName
FROM Data d
CROSS APPLY OPENJSON(CONCAT(N'[', d.OrderId, N']')) j1
CROSS APPLY OPENJSON(CONCAT(N'["', REPLACE(d.OrderName, N':', N'","'), N'"]')) j2
WHERE j1.[key] = j2.[key]
Result:
-----------------
OrderId OrderName
-----------------
11 A
12 B
13 C
14 D
15 E
16 F
17 G
18 H