sqlserver中实现split分割字符串函数

常用的.

IF OBJECT_ID (N'fn_split') IS NOT NULL
DROP FUNCTION  fn_split
go
CREATE  function dbo.fn_split
(
@inputstr varchar(8000),
@seprator varchar(10),
@p int                   --要取第几个数据,从0开始,如果要返回分割后的数组列表清删除--##部分即可
)
returns @temp table (a varchar(200))
as

begin
 declare @i int
 declare @n int  --记录循环的次数
 set @inputstr = rtrim(ltrim(@inputstr))
 set @i = charindex(@seprator, @inputstr)
 SET @n =0        --##

  WHILE @i>=1
 begin
  IF  @p=@n  --##
   begin
     insert @temp values(left(@inputstr, @i - 1))
   end
  set @inputstr = substring(@inputstr, @i + 1, len(@inputstr) - @i)
  set @i = charindex(@seprator, @inputstr)
  SET @n = @n+1 --##
 END

if @inputstr <> '' --最后一位
 IF  @p=@n         --##
  insert @temp values(@inputstr)
return
end
go

 

 

 

方法一 
CREATE  FUNCTION uf_StrSplit '1.1.2.50','.'
(@origStr varchar(7000),  --待拆分的字符串
@markStr varchar(100))  --拆分标记,如','
RETURNS @splittable table
(
str_id  varchar(4000) NOT NULL, --编号ID
string  varchar(2000) NOT NULL --拆分后的字符串
)
AS
BEGIN
declare @strlen int,@postion int,@start int,@sublen int,
@TEMPstr varchar(200),@TEMPid int
SELECT @strlen=LEN(@origStr),@start=1,@sublen=0,@postion=1,
@TEMPstr='',@TEMPid=0
if(RIGHT(@origStr,1)<>@markStr )
begin
set @origStr = @origStr + @markStr
end
WHILE((@postion<=@strlen) and (@postion !=0))
BEGIN
IF(CHARINDEX(@markStr,@origStr,@postion)!=0)
BEGIN
SET @sublen=CHARINDEX(@markStr,@origStr,@postion)-@postion;
END
ELSE
BEGIN
SET @sublen=@strlen-@postion+1;
END
IF(@postion<=@strlen)
BEGIN
SET @TEMPid=@TEMPid+1;
SET @TEMPstr=SUBSTRING(@origStr,@postion,@sublen);
INSERT INTO @splittable(str_id,string)
values(@TEMPid,@TEMPstr)
IF(CHARINDEX(@markStr,@origStr,@postion)!=0)
BEGIN
SET @postion=CHARINDEX(@markStr,@origStr,@postion)+1
END
ELSE
BEGIN
SET @postion=@postion+1
END
END
END
RETURN
END
方法二
create function dbo.fn_split
(
@inputstr varchar(8000),
@seprator varchar(10)
)
returns @temp table (a varchar(200))
as

begin
declare @i int

set @inputstr = rtrim(ltrim(@inputstr))
set @i = charindex(@seprator, @inputstr)

while @i >= 1
begin
insert @temp values(left(@inputstr, @i - 1))

set @inputstr = substring(@inputstr, @i + 1, len(@inputstr) - @i)
set @i = charindex(@seprator, @inputstr)
end

if @inputstr <> ''
insert @temp values(@inputstr)

return
end
go

--调用

declare @s varchar(1000)

set @s='Sa1,Sb1,Sc'

select * from dbo.fn_split(@s,',')

drop function dbo.fn_splitsqlserver中实现split分割字符串函数

你可能感兴趣的:(sqlserver)