我做了一些研究,但我一直无法做到/找不到如何将两者放在一起。
我正在尝试从名为doc_filename的字段中获取文件名,减去任何文档路径和扩展名,例如"docs\00010\filename.doc"
应该只是"filename"
。
这有助于删除路径名,但扩展名仍然存在。如何删除它?
由于
SELECT (case when doc_filename like '%\%' then
LTRIM(
RTRIM(
REVERSE(
SUBSTRING(
REVERSE(doc_filename),0, CHARINDEX('\', REVERSE(doc_filename),0)
)
)
)
)
else ''
end)
FROM documents
答案 0 :(得分:1)
举个例子:
DECLARE @fps TABLE(fp VARCHAR(512));
INSERT INTO @fps(fp)VALUES
('\filename.001.doc'),
('docs\00010\filename.doc'),
('docs\00010\filename'),
('filename.doc'),
('filename'),
('\filename'),
('\filename.001.doc');
-- ('.\filename'); --> this one will fail
SELECT
CASE
WHEN CHARINDEX('.',REVERSE(fp))=0 AND CHARINDEX('\',REVERSE(fp))=0 THEN fp
WHEN CHARINDEX('.',REVERSE(fp))=0 THEN RIGHT(fp,CHARINDEX('\',REVERSE(fp))-1)
WHEN CHARINDEX('\',REVERSE(fp))=0 THEN LEFT(fp,LEN(fp)-CHARINDEX('.',REVERSE(fp)))
ELSE SUBSTRING(fp,LEN(fp)-CHARINDEX('\',REVERSE(fp))+2,CHARINDEX('\',REVERSE(fp))-CHARINDEX('.',REVERSE(fp))-1)
END AS [file_name]
FROM
@fps;
结果:
+--------------+
| file_name |
+--------------+
| filename.001 |
| filename |
| filename |
| filename |
| filename |
| filename |
| filename.001 |
+--------------+