有時咱們要用到批量操做時都會對字符串進行拆分,但是SQL Server中卻沒有自帶Split函數,因此要本身來實現了。ide
-- ============================================= -- Author: chenlong -- Create date: 2015-02-02 -- Description: 根據逗號分隔拆分字符串,返回table -- ============================================= ALTER FUNCTION [dbo].[fn_SplitString] ( @Input nvarchar(max), --輸入字符串 @Separator nvarchar(max)=',', --分隔符 @RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string ) RETURNS @TABLE table ( [Id] int identity(1,1), [Value] nvarchar(max) ) AS BEGIN -- Declare the return variable here 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 @TABLE([Value]) 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 @TABLE([Value]) Values(@Entry) end return END
如何使用:函數
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
例如根據某表的ID保存排序:blog
update a set a.[Order]=t.[Id]
from [dbo].[表] as a join [dbo].SplitString('1,2,3', ',', 1) as t on a.[Id]=t.[Value]
排序
具體的應用請根據本身的狀況來吧:)ip
方法二:element
Create function [dbo].[f_split](@aString varchar(max),@pattern varchar(10)) returns @temp table(r int,a varchar(100)) --實現split功能 的函數 -- select a from dbo.f_split('我:們a:a:b: ',':') as begin declare @i int declare @row int set @row=1 set @aString=rtrim(ltrim(@aString)) set @i=charindex(@pattern,@aString) while @i>=1 begin insert @temp values(@row,left(@aString,@i-1)) set @aString=right(@aString,len(@aString)-@i) set @i=charindex(@pattern,@aString) set @row=@row+1 end if @aString<>'' insert @temp values(@row,@aString) return end