从文件夹数和文件名长度可变的字段中提取最后一个文件名

时间:2016-04-25 14:03:36

标签: sql string

我正在尝试从分区为/的SQL中的字段中提取最后一个文件名,并且在最后一个文件名后面也有一个。 (我使用它在BI网络智能文档中创建一个新的文件。)

Filename1/filename2/filename3/filename4/结果需要Filename4

File1/file2/file3/file4/file5/file6结果需要file6

我尝试了各种组合但没有成功。如您所见,文件名不是标准长度,文件夹数量是可变的。

对此的任何帮助都会非常感激。

谢谢

林恩

2 个答案:

答案 0 :(得分:0)

根据您对我的评论的回答...您是否有一个以" /"结尾的输入字符串;或不 ?我已使用SQL 2008将这两种类型的测试字符串放在此查询中作为dbms。只需注释掉Set @tstString即可运行每个条件,您将看到两种结果可能性。

Declare @tmpFirstMark int
Declare @tmpLastMark int
Declare @tmpUseMark int

Declare @tstString varchar(100)
Set @tstString = 'Filename1/filename2/filename2/filename4/'
Set @tstString = 'File1/file2/file3/file4/file5/file6'

-- Calculate 1st Occurrence of "/"
Set @tmpFirstMark = PATINDEX('%/%',@tstString)
-- Calculate last Occurrence of "/"
Set @tmpLastMark = (LEN(@tstString) - PATINDEX('%/%',REVERSE(@tstString)) + 1)
-- Calculate 2nd to last Occurrence of "/"
Set @tmpUseMark = @tmpLastMark - PATINDEX('%/%', REVERSE(SUBSTRING(@tstString, 1, @tmpLastMark-1)))

Select
    @tstString
    ,@tmpFirstMark
    ,@tmpLastMark
    ,@tmpUseMark

    ,SUBSTRING(@tstString, @tmpLastMark + 1, LEN(@tstString)) as 'resultSTR'
    ,SUBSTRING(@tstString, @tmpUseMark + 1, @tmpLastMark-@tmpUseMark-1) as 'otherResult'

答案 1 :(得分:0)

我会使用正则表达式来检索所需的输出:

([^/]+)/?$

这将在字符串结尾之前匹配尽可能多的非/个字符(至少1个),后面可以跟一个可选的/
您将需要使用匹配的第一组来检索目录的文件名,而不会跟踪/

你没有指定你的RDBMS,我在SQL中使用regexp并不那么舒服,所以我希望你能用你的SQL方言将它们拼凑在一起。