码迷,mamicode.com
首页 > 数据库 > 详细

写自己需要的SQL function

时间:2014-11-07 14:39:01      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   div   on   

在SQL中如何写一个SplitStringFunction,话不多说,上代码:

 1 SET ANSI_NULLS ON
 2 GO
 3 SET QUOTED_IDENTIFIER ON
 4 GO
 5 
 6 CREATE function [dbo].[SplitString]
 7 (
 8     @Input nvarchar(max),    --要分割的字符串
    @Separator nvarchar(max)=,, --分隔符,可以是一个字符也可以是多个字符 9 @RemoveEmptyEntries bit=1 ) --是否移除空字符串 10 returns @TABLE table --返回一个存放已经分割好的字符串的table 11 ( 12 [Id] int identity(1,1), 13 [Value] nvarchar(max) 14 ) 15 as 16 begin 17 declare @Index int, @Entry nvarchar(max) 18 set @Index = charindex(@Separator,@Input) 19 20 while (@Index>0) 21 begin 22 set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) 23 24 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>‘‘) 25 begin 26 insert into @TABLE([Value]) Values(@Entry) 27 end 28 29 set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) 30 set @Index = charindex(@Separator, @Input) 31 end 32 33 set @Entry=ltrim(rtrim(@Input)) 34 if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>‘‘) 35 begin 36 insert into @TABLE([Value]) Values(@Entry) 37 end 38 39 return 40 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)

结果:

bubuko.com,布布扣

 

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

 

写自己需要的SQL function

标签:style   blog   io   color   ar   os   sp   div   on   

原文地址:http://www.cnblogs.com/jerrylucky/p/4081054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!