在SQL中获取两个字符之间的子字符串并删除所有空格

时间:2014-04-10 10:13:53

标签: sql-server

我有一个字符串,如:

Games/Maps/MapsLevel1/Level 1.swf
Games/AnimalWorld/Animal1.1/Level 1.1.swf
Games/patterns and spatial understanding/Level 13.5/Level 13.5.swf

我想只获得没有扩展名(String After last Slash and before Last dot)的文件名,即Level 1和Level 1.1以及Level 13.5,甚至我想删除所有空格,最后的字符串应该是小写的,即最终的输出应该是

level1
level1.1
level13.5 and so on..

我尝试了以下查询,但我得到了Level 1.swf,我如何更改此查询?

SELECT SUBSTRING(vchServerPath, LEN(vchServerPath) - CHARINDEX('/', REVERSE(vchServerPath)) + 2, LEN(vchServerPath)) FROM Games

3 个答案:

答案 0 :(得分:1)

SELECT (left((Path), LEN(Path) - charindex('.', reverse(Path))))
FROM 
(
    SELECT SUBSTRING(vchServerPath, 
                     LEN(vchServerPath) - CHARINDEX('/', REVERSE(vchServerPath)) + 2, 
                     LEN(vchServerPath)) Path
    FROM Games
) A

这样可以工作,我保留了你的内部子串,让你分道扬and,我添加了点的剥离。

我已经包含了一个sql小提琴链接,供您查看动作sql fiddle

<强>编辑: 以下将删除空格并返回小写...

SELECT REPLACE(LOWER((left((Path), LEN(Path) - charindex('.', reverse(Path))))), ' ', '')
FROM 
(
    SELECT SUBSTRING(vchServerPath, 
                     LEN(vchServerPath) - CHARINDEX('/', REVERSE(vchServerPath)) + 2, 
                     LEN(vchServerPath)) Path
    FROM Games
) A

答案 1 :(得分:0)

试试这个:

select
 case 
 when vchServerPath is not null
 then reverse(replace(substring(reverse(vchServerPath),charindex('.',reverse(vchServerPath))+1, charindex('/',reverse(vchServerPath))-(charindex('.',reverse(vchServerPath))+1)),' ',''))
 else ''
end

答案 2 :(得分:0)

这应该可以正常工作;删除了扩展名。

select 
REVERSE(
SUBSTRING(
reverse('Games/patterns and spatial understanding/Level 13.5/Level 13.5.swf'),
5,
(charindex('/',
reverse('Games/patterns and spatial understanding/Level 13.5/Level 13.5.swf')) - 5)
))