Technical Article

Splitting the string with unique delimiter.

,

 

The function can be executed is as shown below

select * from dbo.FSplitColumns('SQLSERVER2000//SQLSERVER2000//SQL SERVER 2008','//')

  1. In the above example,the first argument is a string SQLSERVER2000//SQLSERVER2000//SQL SERVER 2008' has a delimter // and its the second argument of the funtion.
  2. The output is given below
  3. .
CREATE FUNCTION dbo.FSplitColumns
(
@StringArray VARCHAR(8000),
@Delimiter VARCHAR(10)
)
RETURNS
-- The ouput has been captured in @Results table datatype
@Results TABLE
(
id INT IDENTITY(1, 1), 
Item VARCHAR(8000)
)
AS
BEGIN
DECLARE @Next INT,
@lenStringArray INT,
@lenDelimiter INT,
@i INT

SELECT  @i=1, 
@lenStringArray=LEN(@StringArray),
@lenDelimiter=LEN(@Delimiter)

WHILE @i<=@lenStringArray
BEGIN
--find the next occurrence of the delimiter in the stringarray 
SELECT @next=CHARINDEX(@Delimiter, @StringArray + @Delimiter, @i) 
INSERT INTO @Results (Item)
SELECT SUBSTRING(@StringArray, @i, @Next - @i) 
SELECT @i=@Next+@lenDelimiter 
END 
RETURN 
END

Rate

3.29 (7)

You rated this post out of 5. Change rating

Share

Share

Rate

3.29 (7)

You rated this post out of 5. Change rating