/*
=====================================================
**Type:function
**ObjectName:dbo.Daven_Fun_SplitString
**Creater:Daven Shan
**Createdate: 2016-07-25
**Description:split string to table
**eg:select * from dbo.Daven_Fun_SplitString('1,2,3',',',1)
=====================================================
*/
if object_id('Daven_Fun_SplitString') is not null
drop function Daven_Fun_SplitString
go
create function Daven_Fun_SplitString(
@Input nvarchar(max),--input string to be separated
@Separator nvarchar(max)=',', --a string that delimit the substrings in the input string
@RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string
)
returns @tempTable table(
val nvarchar(max)
)
as
begin
declare @Index int, @Entry nvarchar(max)
set @Index = charindex(@Separator,@Input)
while (@Index>0)
begin
set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
begin
insert into @tempTable(val) Values(@Entry)
end
set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
set @Index = charindex(@Separator, @Input)
end
set @Entry=ltrim(rtrim(@Input))
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
begin
insert into @tempTable(val) Values(@Entry)
end
return
end
go