一、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),'')
end
insert @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
end
return
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
end
return @length
end