0

I have a table with thousands of rows like the below (fake names):

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

What I'm needing to do is pull out the codes so I have a listing of:

 C0001506
 C0001516
 C0001517
 C0001518
 C0001519
 C0001520

So far I have this:

select SUBSTRING ( FileName ,PatIndex('%-%', FileName + '5'),8)
from [FileNames]

which returns me "- C00015" for example.

Anyone have any ideas how to make this Substring work?

2
  • Are they in the same position and the same length always? Commented Nov 3, 2017 at 1:31
  • If possible, would be good if it could be guaranteed to pick it up correctly. Commented Nov 3, 2017 at 1:33

1 Answer 1

1

This will do the job:

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

Results:

+--------------------------------------------------------+------------+
|                          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

Update:

Here is another way to do it using LEFT(), PATINDEX() and SUBSTRING() functions:

SELECT *, 
       LEFT(SUBSTRING(STR, PATINDEX('%- %', STR) + 2, LEN(STR) ), 8) AS Result
FROM @T
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that Sami :)
@James Glad to help :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.