1

I have the below query:

Select
    Notes
From
    Table

And a sample out put may be:

78652972MWGN00183HCE736430
77305311FTBCHCE735946Wheat
Training

However is what I would like as the output is an ID within the string, the ID always starts with HCE and is always 8 characters long, and where the is no ID, it would return No Machine ID

So my desired out put for the above would be:

HCE736430
HCE735946
No Machine Id

How can I achieve this ?

I have looked at using SUBSTRING, but cannot search for the HCE part.

I am currently doing this in Excel using MID and SEARCH:

=MID(A2,SEARCH("HCE",A2),9)
1

3 Answers 3

5

You can use PATINDEX for this. Here is an example.

declare @Something table (SomeVal varchar(50))

insert @Something values
('78652972MWGN00183HCE736430')
, ('77305311FTBCHCE735946Wheat')
, ('Training')
,('asdfHCExx')



select case when patindex('%HCE[0-9a-z][0-9a-z][0-9a-z][0-9a-z][0-9a-z]%', SomeVal) > 0
    then substring(SomeVal, patindex('%HCE[0-9a-z][0-9a-z][0-9a-z][0-9a-z][0-9a-z]%', SomeVal), 9)
    else 'No Machine Id'
end

from @Something
Sign up to request clarification or add additional context in comments.

1 Comment

I updated this to handle a length of 8 characters. Not very clear what the OP expects for valid characters.
2

This query does what you are asking for:

SELECT CASE WHEN  CHARINDEX('HCE', Notes) = 0 THEN 'No MachineID' ELSE 
SUBSTRING(Gender, CHARINDEX('HCE', Notes), 9) END
FROM  Table

3 Comments

This may return false positives if they have HCE in the string not followed by 6 digits.
That was not part of the specification, actually.
"the ID always starts with HCE and is always 8 characters long". This isn't necessarily incorrect, just saying it could possibly return false positives.
2

You can use patindex() with substring() :

SELECT Notes, SUBSTRING(Notes, PATINDEX('%HCE%', Notes +'HCE'), 9)
From Table;

First version will display blank if the Machine Id note found if you want to display No Machine Id instead then you can add case expression :

(CASE WHEN PATINDEX('%HCE%', Notes) > 0
      THEN SUBSTRING(Notes, PATINDEX('%HCE%', Notes), 9)
      ELSE 
      'No Machine Id'
 END)

3 Comments

This may return false positives if they have HCE in the string not followed by 6 digits.
@SeanLange. . . I have a read this the ID always starts with HCE and is always 8 characters long,
Maybe it is just characters and I interpreted it as digits. But This could still return false positives if HCE falls towards then end. Not saying this is wrong, just saying it may return false positives. :)

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.