写自己需要的SQL function

在SQL中如何写一个SplitStringFunction,话不多说,上代码:

 1 SET ANSI_NULLS ON
 2 GO
 3 SET QUOTED_IDENTIFIER ON
 4 GO
 5 
 6 CREATE function [dbo].[SplitString]
 7 (
 8     @Input nvarchar(max),    --要分割的字符串
    @Separator nvarchar(max)=',', --分隔符,可以是一个字符也可以是多个字符 9 @RemoveEmptyEntries bit=1 ) --是否移除空字符串 10 returns @TABLE table --返回一个存放已经分割好的字符串的table 11 ( 12 [Id] int identity(1,1), 13 [Value] nvarchar(max) 14 ) 15 as 16 begin 17 declare @Index int, @Entry nvarchar(max) 18 set @Index = charindex(@Separator,@Input) 19 20 while (@Index>0) 21 begin 22 set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) 23 24 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 25 begin 26 insert into @TABLE([Value]) Values(@Entry) 27 end 28 29 set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) 30 set @Index = charindex(@Separator, @Input) 31 end 32 33 set @Entry=ltrim(rtrim(@Input)) 34 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') 35 begin 36 insert into @TABLE([Value]) Values(@Entry) 37 end 38 39 return 40 end

function和table都准备好,接下来测试:

declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max)

set @str1 = '1,2,3'
set @str2 = '1###2###3'
set @str3 = '1###2###3###'

select [Value] from [dbo].[SplitString](@str1, ',', 1)
select [Value] from [dbo].[SplitString](@str2, '###', 1)
select [Value] from [dbo].[SplitString](@str3, '###', 0)

结果:

 

里面还有个自增的[Id]字段哦,在某些情况下有可能会用上的,例如根据Id来保存排序等等。

 

posted on 2014-11-07 13:02  Jerry_zhang  阅读(374)  评论(0编辑  收藏  举报

导航