寫本身須要的SQL function

在SQL中如何寫一個SplitStringFunction,話很少說,上代碼:ide

 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)

結果:spa

 

裏面還有個自增的[Id]字段哦,在某些狀況下有可能會用上的,例如根據Id來保存排序等等。code

相關文章
相關標籤/搜索