Splitting string in SQL Server

For sql server 2016 before, Try to create user defined function like below and use it

CREATE FUNCTION [dbo].[SplitString]

@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS @Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE @StartIndex INT, @EndIndex INT

SET @StartIndex = 1
IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
BEGIN
SET @Input = @Input + @Character
END

WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)

INSERT INTO @Output(Item)
SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
END

RETURN
END


SELECT * FROM [SplitString]('John,Jeremy,Jack',',')


You can use the below statement for split the string in sql. It is available in 2016 onwards

SELECT * FROM STRING_SPLIT('John,Jeremy,Jack',',')


Comments

Popular posts from this blog

Email Sending through O365 using OAuth Protocol

IoT Technology

What is reverse proxy?