I am trying to split a row into two rows depending on the value in a cell on that row. For example, I have the following table structure (it's a temporary table without any keys, indexes or anything whatsoever and i can select the split results in another temporary table):
Col1 | Col2
a | one
b | two
c | three
d | one two
e | one two
Then it it should be split into:
Col1 | Col2
a | one
b | two
c | three
d | one
d | two
e | one
e | two
The problem is that I can't understand how to start, I found these two questions, which are similar, in my case it's an empty string instead:
I will do this using XML
SELECT col1,
Split.a.value('.', 'VARCHAR(100)') col2
FROM (SELECT col1,
col2,
Cast ('<M>' + Replace(col2, ' ', '</M><M>') + '</M>' AS XML) AS Data
FROM Yourtable) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
You can use a UDF
to handle the splitting of the strings and run it over each of your results. Here's something I got working fairly quickly:
Create FUNCTION [dbo].[fnSplit](@text varchar(MAX), @delimiter varchar(20) = ' ')
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(MAX)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
Test data:
Create Table #Temp
(
Col1 Varchar (20),
Col2 Varchar (20)
)
Insert #Temp
Values ('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'one two'), ('e', 'one two')
Query:
Select Col1, Value[Col2]
From #Temp T
Cross Apply dbo.fnSplit(T.col2, ' ')
And results:
Col1 Col2
a one
b two
c three
d one
d two
e one
e two
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.