Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get all of them after the second "_" separation in a string data in mssql?

I have data like this in a string column in a table: [Product] -> "LA100_Runner_35C924_D". From this data I want to get the data after the second _, so I want to get 35C924_D.

How do I do that?

I tried WHERE [Product] LIKE '%_%' escape '' but I couldn’t quite get it working. I can’t think of what I want with the LIKE operation.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option is to apply the combination of SUBSTRING + PATINDEX twice on the same strings, while splitting on the first underscore symbol as follows:

WITH cte AS (
    SELECT SUBSTRING(string, PATINDEX('%[_]%', string)+1, LEN(string)) AS string
    FROM tab
)
SELECT SUBSTRING(string, PATINDEX('%[_]%', string)+1, LEN(string))
FROM cte

Check the demo here.


You can also do the same using RIGHT + PATINDEX in a very similar fashion:

WITH cte AS (
    SELECT RIGHT(string, LEN(string) - PATINDEX('%[_]%', string)) AS string
    FROM tab
)
SELECT RIGHT(string, LEN(string) - PATINDEX('%[_]%', string)) AS string
FROM cte

Check the demo here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading