0

Basically, the problem is I have a SELECT statement like so:

SELECT sys_connect_by_path(name, '/')

Which gives me output like this:

/Name of Folder I want/Another folder...../Folder I'm looking from

And I would like to cut everything out and just have the first folder's name. What would be the best way to go about doing this?

4

2 回答 2

0

如果您有一个包含类似 unix 的文件路径(目录甚至可能是文件)列表的 files 表,您可以使用类似于以下内容的查询来检索结果作为文件管理器显示:

SELECT f.file_path,
  SUBSTR(f.file_path, 1, INSTR(f.file_path, '/', -2)) AS parent_file_path
  FROM files_tbl f 
  START WITH (f.file_path = '/') -- Start with the root directory path
  CONNECT BY PRIOR f.file_path = SUBSTR(f.file_path, 1, INSTR(f.file_path, '/', -2))
  ORDER SIBLINGS BY parent_file_path ASC NULLS FIRST, f.file_path ASC;

此查询假定目录在 file_path 中以 / 结尾/结束,并且文件不会:

/
/folder/
/folder/file.log
/folder/subfolder/
/folder/subfolder/example.txt
于 2013-10-03T20:54:20.200 回答
0

尝试:

SELECT substr(str, instr(str, '/', -1) + 1)
  FROM (
    SELECT '/Name of Folder I want/Another folder...../Folder Im looking from' AS str FROM dual
  )
;

instr的“-1”参数告诉 Oracle 从末尾开始返回第一次出现的“/”字符。

编辑:对不起,我读错了,另一个建议(丑陋的):

SELECT substr(str, 2, CASE
                        WHEN instr(str, '/', 2, 1) > 0 THEN instr(str, '/', 2, 1) - 2
                        ELSE length(str) - 1
                      END)
  FROM (
    SELECT '/Name of Folder I want/Another folder...../Folder Im looking from' AS str FROM dual
    UNION ALL
    SELECT '/Name of Folder I want' AS str FROM dual
  )
;

正则表达式提供了另一种可能的解决方案,尽管我们正在处理的字符串必须将“/”字符连接到末尾:

SELECT regexp_substr(str || '/', '/(.*?)/', 1, 1, NULL, 1)
  FROM (
    SELECT '/Name of Folder I want/Another folder...../Folder Im looking from' AS str FROM dual
    UNION ALL
    SELECT '/Name of Folder I want' AS str FROM dual
  )
;

这里我们利用了子表达式 - *regexp_substr* 的最后一个参数告诉 Oracle 只返回第一对括号内的字符串部分。

于 2013-10-03T20:34:46.813 回答