I want a split function in SQL server. I came across this thread: Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous
and I feel it is doing too many calculations using index etc. I wrote this function:
ALTER FUNCTION [dbo].[Split]
(
@Data varchar(8000),
@Delimter char(1) = ','
)
RETURNS @RetVal TABLE
(
Data varchar(8000)
)
AS
Begin
Set @Data = RTrim(Ltrim(IsNull(@Data,'')))
Set @Delimter = IsNull(@Delimter,',')
If Substring(@Data,Len(@Data),1) <> @Delimter
Begin
Set @Data = @Data + @Delimter
End
Declare @Len int = Len(@Data)
Declare @index int = 1
Declare @Char char(1) = ''
Declare @part varchar(8000) = ''
While @index <= @Len
Begin
Set @Char = Substring(@Data,@index,1)
If @Char = @Delimter And @part <> ''
Begin
Insert into @RetVal Values (@part)
Set @part = ''
End
Else
Begin
Set @part = @part + @Char
End
Set @index = @index + 1
End
RETURN;
End
Can anybody comment which one is efficient? I will be using this function too much for splitting the data for one of my scrapping application and I want this to be efficient. Also please mention how did you measure it's efficiency.