sql 字符串截取,获取想要的结果

img


怎么由字符串转换为1,2,3,4这样的四个字段呢,用了很多办法都不知道怎么获取,不知道怎么解决,有人知道嘛


ALTER FUNCTION [dbo].[cutStr]
(
@s varchar(8000), --要区分的字段
@pos int, --要获取的数据项的位置
@split varchar(10) --数据分隔符
)RETURNS varchar(1000)
AS
BEGIN
IF @s IS NULL RETURN(NULL)
DECLARE @splitlen int
SELECT @splitlen=LEN(@split+'a')-2
WHILE @pos>1 AND CHARINDEX(@split,@s+@split)>0
SELECT @pos=@pos-1,
@s=STUFF(@s,1,CHARINDEX(@split,@s+@split)+@splitlen,' ')

RETURN(ISNULL(LEFT(@s,CHARINDEX(@split,@s+@split)-1),' ')) 
end

img

mysql
select substring_index( substring_index('aaa>bbb>ccc>ddd', '>', 1 ), '>',- 1 ) -- 第一个字符串
select substring_index( substring_index('aaa>bbb>ccc>ddd', '>', 2 ), '>',- 1 ) -- 第二个字符串
..以此类推

字段数固定吗?
比如四个或者几个,如果固定直接用函数分隔处理就可以,如果不固定得需要写动态语句执行了


--主要用到length函数取长度,instr定位,substr截取
with t as
 (select str1.a,
         length(a) le,--字符串长度
         length(a) - length(replace(a, '>', '')) cn,--'>'个数
         instr(a, '>', 1) b,--第一个'>'位置
         instr(a, '>', instr(a, '>', 1) + 1) c,--第二个'>'位置
         instr(a, '>', instr(a, '>', instr(a, '>', 1) + 1) + 1) d,--第三个'>'位置
         instr(a,
               '>',
               instr(a, '>', instr(a, '>', instr(a, '>', 1) + 1) + 1) + 1) e
    from str1)--第四个'>'位置,以此类推

select t.a,
       (case
         when t.cn > 0 then
          substr(a, 1, b - 1)
         when t.cn = 0 then
          a
       end) as "1",
       (case
         when t.cn > 1 then
          substr(a, b + 1, c - b - 1)
         when t.cn = 1 then
          substr(a, b + 1, le - b)
       end) as "2",
       (case
         when t.cn > 2 then
          substr(a, c + 1, d - c - 1)
         when t.cn = 2 then
          substr(a, c + 1, le - c)
       end) as "3",
       (case
         when t.cn > 3 then
          substr(a, d + 1, e - d + 1)
         when t.cn = 3 then
          substr(a, d + 1, le - d)
       end) as "4"
  from t;