我有一个包含数千行的表,如下所示(假名):
C:\James\AAA(1) - C0001506 Mrs Michaela Hysell.pdf
C:\James\AAA(10) - C0001516 Mrs Delfina Cardoza.pdf
C:\James\AAA(11) - C0001517 Mrs Melony Pickle.pdf
C:\James\AAA(12) - C0001518 Mr Homer Guillot.pdf
C:\James\AAA(13) - C0001519 Mrs Lawerence Matis.pdf
C:\James\AAA(14) - C0001520 Mrs Yahaira Hausner.pdf
我需要做的是取出代码,以便列出:
C0001506
C0001516
C0001517
C0001518
C0001519
C0001520
到目前为止,我有这个:
select SUBSTRING ( FileName ,PatIndex('%-%', FileName + '5'),8)
from [FileNames]
返回我" - C00015"例如。
任何人都有任何想法如何使这个子串工作?
答案 0 :(得分:1)
这将完成这项工作:
DECLARE @T TABLE ( STR VARCHAR(MAX));
INSERT INTO @T VALUES
('C:\James\AAA(1) - C0001506 Mrs Michaela Hysell.pdf'),
('C:\James\AAA(10) - C0001516 Mrs Delfina Cardoza.pdf'),
('C:\James\AAA(11) - C0001517 Mrs Melony Pickle.pdf'),
('C:\James\AAA(12) - C0001518 Mr Homer Guillot.pdf'),
('C:\James\AAA(13) - C0001519 Mrs Lawerence Matis.pdf'),
('C:\James\AAA(14) - C0001520 Mrs Yahaira Hausner.pdf');
SELECT *,
SUBSTRING(STR, CHARINDEX('-', STR, 0)+1, CHARINDEX('-', STR, 0)-8 ) AS Result
FROM @T
结果:
+--------------------------------------------------------+------------+
| STR | Result |
+--------------------------------------------------------+------------+
| C:\James\AAA(1) - C0001506 Mrs Michaela Hysell.pdf | C0001506 |
| C:\James\AAA(10) - C0001516 Mrs Delfina Cardoza.pdf | C0001516 |
| C:\James\AAA(11) - C0001517 Mrs Melony Pickle.pdf | C0001517 |
| C:\James\AAA(12) - C0001518 Mr Homer Guillot.pdf | C0001518 |
| C:\James\AAA(13) - C0001519 Mrs Lawerence Matis.pdf | C0001519 |
| C:\James\AAA(14) - C0001520 Mrs Yahaira Hausner.pd222f | C0001520 |
+--------------------------------------------------------+------------+
<强> Demo 强>
更新
以下是使用LEFT()
,PATINDEX()
和SUBSTRING()
函数执行此操作的另一种方法:
SELECT *,
LEFT(SUBSTRING(STR, PATINDEX('%- %', STR) + 2, LEN(STR) ), 8) AS Result
FROM @T