Today I will tell you how to split string in SQL Server.
CREATE FUNCTION SPLIT_STRING(@String NVARCHAR(MAX), @Delimiter CHAR(1))
RETURNS @Temptable TABLE(ID NVARCHAR(512))
AS
BEGIN
DECLARE @INDEX int, @SLICE VARCHAR(8000)
SELECT @INDEX = 1
IF LEN(@String) < 1 OR @String IS NULL
return
WHILE @INDEX != 0
BEGIN
SET @INDEX = CHARINDEX(@Delimiter, @String)
IF @INDEX != 0
BEGIN
SET @SLICE = LEFT(@String, @INDEX - 1)
END
ELSE
BEGIN
SET @SLICE = @String
END
IF(LEN(@SLICE) > 0)
BEGIN
INSERT INTO @Temptable(ID) VALUES(@SLICE)
END
SET @String = RIGHT(@String, LEN(@String) - @INDEX)
IF LEN(@String) = 0
break
END
RETURN
END
SELECT * FROM dbo.SPLIT_STRING('Mousa,Alsheikh,Blog', ',');
SELECT * FROM dbo.SPLIT_STRING('Pizza is my favourite food', ' ');