Friday, March 28, 2014

Split Function in Sql server

create  FUNCTION [dbo].[SplitFun](
    @sInputList VARCHAR(2000) -- List of delimited items
  , @sDelimiter VARCHAR(1) = '|' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(50))


BEGIN

DECLARE @sItem VARCHAR(50)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END

No comments:

Post a Comment