复制代码代码如下:SETANSI_NULLSONGOSETQUOTED_IDENTIFIERONGOCREATEfunction[dbo].[SplitString](@Inputnvarchar(max),@Separatornvarchar(max)=',',@RemoveEmptyEntriesbit=1)returns@TABLEtable([Id]intidentity(1,1),[Value]nvarchar(max))asbegindeclare@Indexint,@Entrynvarchar(max)set@Index=charindex(@Separator,@Input)while(@Index>0)beginset@Entry=ltrim(rtrim(substring(@Input,1,@Index-1)))if(@RemoveEmptyEntries=0)or(@RemoveEmptyEntries=1and@Entry<>'')begininsertinto@TABLE([Value])Values(@Entry)endset@Input=
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
函数、表都建好了,下面调用测试一下吧:
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 里面 自定义 Split 完成 个性化 需求
声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!