I´m new to SQL Server and I'm dealing with this following problem.
Let's say I have a column that looks like that:
ID String
-------------------------
1 Today is a good day!
2 Whatever
3 Hello my friend
So my goal was to split these sentences into this:
ID String1 String2 String3 String4 String5
------------------------------------------------------
1 Today is a good day!
2 Whatever
3 Hello my friend
I tried using this code:
CREATE FUNCTION [dbo].[SplitString]
(@str nvarchar(max),
@separator char(1))
RETURNS TABLE
AS
RETURN (
WITH tokens(p, a, b) AS
(
SELECT
CAST(1 AS BIGINT),
CAST(1 AS BIGINT),
CHARINDEX(@separator, @str)
UNION ALL
SELECT
p + 1,
b + 1,
CHARINDEX(@separator, @str, b + 1)
FROM
tokens
WHERE
b > 0
)
SELECT
--p-1 ItemIndex,
SUBSTRING(@str, a,
CASE WHEN b > 0 THEN b-a
ELSE LEN(@str)
END) AS Item
FROM tokens)
GO
which I found here at Stackoverflow.
It seems to work, for single strings, but its not working for multiple strings. And it puts every word in a new row like this:
Item
Today
is
a
good
day!
So how do I adjust the code, so it does the desired?
One more problem is, that I don´t really know the # of words in each string.
So it could differ, e.g. from 1 word to 100 words.
I would be very happy if someone could help me with this problem, as I´m only starting to learn how to use SQL.
Thanks! MG