您的位置:首页 > 数据库

写自己需要的SQL function

2014-11-07 13:02 316 查看
在SQL中如何写一个SplitStringFunction,话不多说,上代码:

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 --返回一个存放已经分割好的字符串的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


function和table都准备好,接下来测试:

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来保存排序等等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: