简体   繁体   中英

Select only part of a string SQL Server

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)

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM