您的位置:首页 > 数据库

sql自定义函数实现字符串分割Split()功能

2017-05-12 14:38 399 查看
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[SplitString]
(
@Input nvarchar(max),    @Separator nvarchar(max)=',',
@RemoveEmptyEntries bit=1 )
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


调用函数如下:

select [Value] from [dbo].[SplitString](‘胶原蛋白/胶原/胶原水解物/’, ‘/’, 1)

select [Value] from [dbo].[SplitString](‘胶原蛋白/胶原/胶原水解物/’, ‘/’, 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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql 函数