数据库自带的substring()、charindex()函数,可以根据需要截取字符串,但并不能实现分割
自己写分割函数,以下可以参考:
create function GetStr(
@str varchar(1024), --要分割的字符串
@split varchar(10), --分隔符号
@index int --取第几个元素
)
returns varchar(1024)
as
begin
declare @location int
declare @start int
declare @next int
declare @seed int
set @str=ltrim(rtrim(@str))
set @start=1
set @next=1
set @seed=len(@split)
set @location=charindex(@split,@str)
while @location<>0 and @index>@next
begin
set @start=@location+@seed
set @location=charindex(@split,@str,@start)
set @next=@next+1
end
if @location =0 select @location =len(@str)+1
return substring(@str,@start,@location-@start)
end
createfunctionf_split(@cvarchar(2000),@splitvarchar(2))
returns@ttable(colvarchar(20))
as
begin
while(charindex(@split,@c)<>0)
begin
insert@t(col)values(substring(@c,1,charindex(@split,@c)-1))
set@c=stuff(@c,1,charindex(@split,@c),'')
end
insert@t(col)values(@c)
return
end
go
select*fromdbo.f_split('dfkd,dfdkdf,dfdkf,dffjk',',')
dropfunctionf_split
col
--------------------
dfkd
dfdkdf
dfdkf
dffjk
扩展资料
巧用SQL内置函数分割字符串
createfunction[dbo].[fn_char_splitbystr](
@Stringnvarchar(4000),function
@Delimiternvarchar(100)
)
returns@ValueTabletable([FValue]nvarchar(4000),[FSerial]int)
as
begin
declare@valuenvarchar(4000),@valnvarchar(4000)
declare@NextStringnvarchar(4000),@Posint,@NextPosint,@CommaChecknvarchar(1),@idint
set@value=@String
set@id=1
set@NextString=''
set@CommaCheck=right(@value,1)
set@value=@value+@Delimiter+space(len(@Delimiter)-1)
set@Pos=charindex(@Delimiter,@value)
set@NextPos=1
while(@pos<>0)begin
set@NextString=substring(@value,1,@Pos-1)
set@val=@NextString
if@id>1set@val=substring(@val,len(@Delimiter),len(@val))
insertinto@ValueTable([FValue],[FSerial])VALUES(@val,@id)
set@value=substring(@value,@pos+1,LEN(@value))
set@NextPos=@Pos
set@pos=charindex(@Delimiter,@value)
set@id=@id+1
end
return
end
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)