使用SQLite
,我想以下面的方式分割一个字符串.
输入字符串:
C:\Users\fidel\Desktop\Temp
并让查询返回这些行:
C:\ C:\Users\ C:\Users\fidel\ C:\Users\fidel\Desktop\ C:\Users\fidel\Desktop\Temp
换句话说,我想将文件路径拆分为其组成路径.有没有办法在纯SQLite中执行此操作?
这可以使用递归公用表表达式:
WITH RECURSIVE split(s, last, rest) AS ( VALUES('', '', 'C:\Users\fidel\Desktop\Temp') UNION ALL SELECT s || substr(rest, 1, 1), substr(rest, 1, 1), substr(rest, 2) FROM split WHERE rest <> '' ) SELECT s FROM split WHERE rest = '' OR last = '\';
(你没有要求合理的方式.)
递归CTE:
WITH RECURSIVE cte(org, part, rest, pos) AS ( VALUES('C:\Users\fidel\Desktop\Temp', '','C:\Users\fidel\Desktop\Temp'|| '\', 0) UNION ALL SELECT org, SUBSTR(org,1, pos + INSTR(rest, '\')), SUBSTR(rest, INSTR(rest, '\')+1), pos + INSTR(rest, '\') FROM cte WHERE INSTR(rest, '\') > 0 ) SELECT * FROM cte WHERE pos <> 0 ORDER BY pos;
SqlFiddleDemo
输出:
??????????????????????????????? ? part ? ??????????????????????????????? ? C:\ ? ? C:\Users\ ? ? C:\Users\fidel\ ? ? C:\Users\fidel\Desktop\ ? ? C:\Users\fidel\Desktop\Temp ? ???????????????????????????????
这个怎么运作:
org - original string does not change part - simply `LEFT` equivalent of original string taking pos number of chars rest - simply `RIGHT` equivalent, rest of org string pos - position of first `\` in the rest
跟踪:
?????????????????????????????????????????????????????????????????????????????????????????????????? ? org ? part ? rest ? pos ? ?????????????????????????????????????????????????????????????????????????????????????????????????? ? C:\Users\fidel\Desktop\Temp ? C:\ ? Users\fidel\Desktop\Temp\ ? 3 ? ? C:\Users\fidel\Desktop\Temp ? C:\Users\ ? fidel\Desktop\Temp\ ? 9 ? ? C:\Users\fidel\Desktop\Temp ? C:\Users\fidel\ ? Desktop\Temp\ ? 15 ? ? C:\Users\fidel\Desktop\Temp ? C:\Users\fidel\Desktop\ ? Temp\ ? 23 ? ? C:\Users\fidel\Desktop\Temp ? C:\Users\fidel\Desktop\Temp ? ? 28 ? ??????????????????????????????????????????????????????????????????????????????????????????????????
如果要单独搜索值,请使用以下代码:
WITH RECURSIVE split(content, last, rest) AS ( VALUES('', '', 'value1§value2§value3§value4§value5§value6§value7') UNION ALL SELECT CASE WHEN last = '§' THEN substr(rest, 1, 1) ELSE content || substr(rest, 1, 1) END, substr(rest, 1, 1), substr(rest, 2) FROM split WHERE rest <> '' ) SELECT REPLACE(content, '§','') AS 'ValueSplit' FROM split WHERE last = '§' OR rest ='';
结果:
**ValueSplit** value1 value2 value3 value4 value5 value6 value7
我希望我能为遇到同样问题的人提供帮助。