I have a table like this.
id items
1 1|2|3
2 3|4
...
Now, I want to split items to multiple rows, like this.
id item
1 1
1 2
1 3
2 3
2 4
...
Can SQL do this job?
I have a table like this.
id items
1 1|2|3
2 3|4
...
Now, I want to split items to multiple rows, like this.
id item
1 1
1 2
1 3
2 3
2 4
...
Can SQL do this job?
You shouldn't store data in this format in your database due to index usages etc. But in some cases, you can't avoid it, if an foreign application delivers information in this way for example. If you have to store it this way and disaggregate it to store it in a good format you can use the following user defined function to achieve it.
CREATE FUNCTION dbo.udf_split (@String nvarchar(max), @Delimiter nchar(1))
RETURNS @Results Table (Items nvarchar(max))
AS
BEGIN
DECLARE @Index int
DECLARE @Slice nvarchar(max)
SET @Index = 1
IF @String IS NULL RETURN
WHILE @Index != 0
BEGIN
SELECT @Index = CHARINDEX(@Delimiter, @String)
IF @Index != 0
SELECT @Slice = LEFT(@String, @Index - 1)
ELSE
SELECT @Slice = @String
INSERT INTO @Results(Items) VALUES (LTRIM(RTRIM(@Slice)))
SELECT @String = RIGHT(@String, LEN(@String) - @Index)
IF Len(@String) = 0 BREAK
END
RETURN
END
GO