SQL Server分割字串,返回臨時表

2021-07-11 05:28:20 字數 1809 閱讀 5829

一、sql分割字串,返回臨時表

方法一:

create function [dbo].[f_split]

( @c varchar(2000),--需要分割的字串(例如:1,2,3,4,5 我|和|你)

@split varchar(2)--分隔符(例如 , | $)

)returns @t table(col varchar(200))--返回表

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),'')

endinsert @t(col) values (@c)

return

end

方法二:

create function [dbo].[f_split]

( @str varchar(2000),--需要分割的字串(例如:1,2,3,4,5 我|和|你)

@spliter varchar(2)--分隔符(例如 , | $)

)returns @tb table(ch varchar(200))--返回表

as begin

declare @num int,@pos int, @nextpos int

set @num = 0

set @pos = 1

while(@pos <= len(@str))

begin

select @nextpos = charindex(@spliter, @str, @pos)

if(@nextpos = 0 or @nextpos is null)

select @nextpos = len(@str) + 1

insert into @tb values(rtrim(ltrim(substring(@str, @pos, @nextpos - @pos))))

select @pos = @nextpos+1

endreturn

end

二、sql分割字串,返回元素個數

create function f_getarraylength

( @str varchar(2000),--需要分割的字串(例如:1,2,3,4,5 我|和|你)

@split varchar(2)--分隔符(例如 , | $)

)returns int

as begin

declare @location int

declare @start int

declare @length int

set @str=ltrim(rtrim(@str))

set @location=charindex(@split,@str)

set @length=1

while @location<>0

begin

set @start=@location+1

set @location=charindex(@split,@str,@start)

set @length=@length+1

endreturn @length

end

Sqlserver 字串分割

字串分割,返回字串按指定分割符分割後長度 使用 select dbo.fun get strarraylength 1,2,3,4 create function dbo fun get strarraylength str varchar 1024 要分割的字串 split varchar 10 ...

SQL SERVER分割字串

1 使用指定的字串分割,返回分割後元素的個數 create function get strlength str varchar 1024 split varchar 10 returns int asbegin declare location int declare start int decl...

sqlserver 字串分割函式

create function split charstring nvarchar 4000 字串 separator char 1 分割符 returns tb temp table string nvarchar 4000 asbegin declare beginindex int,separ...