实现SQL Server中的切割字符串SplitString函数,返回Table

时间:2022-04-28 14:43:08

有时我们要用到批量操作时都会对字符串进行拆分,可是SQL Server中却没有自带Split函数,所以要自己来实现了。

-- =============================================
-- 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)

执行结果如下图所示:

实现SQL Server中的切割字符串SplitString函数,返回Table

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

例如根据某表的ID保存排序:

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]

具体的应用请根据自己的情况来吧:)

方法二:

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