多语言展示
当前在线:849今日阅读:195今日分享:41

sql分割字符串函数

自定义sql字符串分割函数。结尾有函数脚本。
工具/原料

sql server2012

方法/步骤
1

charindex内置函数返回指定字符所出现的位置。第一个参数为目标字符串,即查找的字符串;第二个参数为被查找的字符串;第三个参数为开始查找位置,为空时默认从第一位查找

2

创建函数。

3

测试函数。

4

函数脚本; create function [dbo].[fn_Split] ( @str varchar(max),    --原字符串 @fgzf varchar(10)     --分割符号 )returns @table table   --返回 ( id int identity(1,1), value varchar(max) )as begin  declare @len int = 1;  declare @len1 int = 1;  declare @count int = 0; set @count = len(@str);  if(@count > 0)  begin    while @len <> 0    begin     set @len1 = @len;    if(@len = 1)     begin      set @len = CHARINDEX(@fgzf,@str,@len);    end     else begin      set @len = CHARINDEX(@fgzf,@str,@len + 1);    end     if(@len1 = 1)    begin      if(@len <> 0)     begin       insert into @table(value)      select SUBSTRING(@str,@len1,@len-1);     end     else begin       insert into @table(value)      select @str;     end     end    else if (@len <> 0) begin      insert into @table(value)     select SUBSTRING(@str,@len1 + 1,@len - @len1 -1);    end     if(@len = 0 and @len1 > 1)     begin      insert into @table(value)     select SUBSTRING(@str,@len1 + 1,len(@str) - @len1);    end    end   end  return; end

推荐信息