Tuesday, January 3, 2017

Split function in sql

Create  FUNCTION [dbo].[fnSplitPosToString] (
 @string VARCHAR(MAX)
 ,@delimiter CHAR(1)
 )

 RETURNS @output TABLE (Id int identity (1,1),data VARCHAR(256))
 
BEGIN
 DECLARE @start INT
     ,@end INT
 
 SELECT @start = 1
  ,@end = CHARINDEX(@delimiter, @string)
 
 WHILE @start < LEN(@string) + 1
 BEGIN
  IF @end = 0
   SET @end = LEN(@string) + 1
 
  INSERT INTO @output (data)
  VALUES (SUBSTRING(@string, @start, @end - @start))
 
  SET @start = @end + 1
  SET @end = CHARINDEX(@delimiter, @string, @start)
 END
 
 RETURN
END

No comments:

Post a Comment