Tuesday, 23 June 2015

Tabular function to split by delimiter in SQL


GO
/****** Object:  UserDefinedFunction [dbo].[FN_SplitStringByDelimiter]    Script Date: 6/23/2015 12:48:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from dbo.[FN_SplitStringByDelimiter] ('goku,goku1,goku2',',')

CREATE FUNCTION [dbo].[FN_SplitStringByDelimiter]

(

@List VARCHAR(8000),   -- String of values

@SplitOn NVARCHAR(5)    -- delimiter value

)

RETURNS @RtnValue TABLE

(

Id INT IDENTITY(1,1),

Component VARCHAR(50)

)

AS

BEGIN

WHILE (CHARINDEX(@SplitOn,@List)>0)

BEGIN


IF LEN(LTRIM(RTRIM(SUBSTRING(@List,1,CHARINDEX(@SplitOn,@List)-1)))) > 0

INSERT INTO @RtnValue (Component)

SELECT Component = LTRIM(RTRIM(SUBSTRING(@List,1,CHARINDEX(@SplitOn,@List)-1)))

SELECT @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List)+LEN(@SplitOn),LEN(@list))

END


IF LEN(LTRIM(RTRIM(@List))) > 0
INSERT INTO @RtnValue (Component)
SELECT Component = LTRIM(RTRIM(@List))

-- Delete StringEmpty and NULL values from List
DELETE FROM @RtnValue WHERE Component is null OR Component=''

RETURN

END

No comments:

Post a Comment