SQLServer中的切割字符串SplitString函数

2022-05-24 0 1,111

复制代码 代码如下:

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

/*

by kudychen 2011-9-28

*/

CREATE function [dbo].[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 @TABLE table

(

[Id] int identity(1,1),

[Value] 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 @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)

执行结果:

里面还有个自增的[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]

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

作者:Kudy

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MsSql SQLServer中的切割字符串SplitString函数 https://www.niceym.com/60438.html