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

Extract a value between 2 pipes

My column has values

1234|aaa4|8752

The length of these values are not fixed.

I want to extract the second value aaa4

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

I tried writing this

SELECT SUBSTRING(column_name,CHARINDEX('|',column_name) + 1, 
CHARINDEX('|',column_name, CHARINDEX('|',column_name)))
FROM [name].[name].[table_name]

With this reference

Trying to extract number between 2 characters '|' MS SQL

But this is not working fine and it is showing text after the second pipe as well

aaa4|8752

It is because we are using substring and the third argument is of the length. So it is taking other characters as well. How do i limit the length to the second pipe?

>Solution :

SELECT SUBSTRING(
    column_name,
    CHARINDEX('|', column_name) + 1,
    CHARINDEX('|', column_name, CHARINDEX('|', column_name) + 1) - CHARINDEX('|', column_name) - 1
) AS extracted_value
FROM [name].[name].[table_name];
  • CHARINDEX('|', column_name) finds the position of the first pipe.
  • CHARINDEX('|', column_name, CHARINDEX('|', column_name) + 1) finds
    the position of the second pipe, starting the search after the first
    pipe.
  • The difference between the positions of the second pipe and the first
    pipe (- 1) gives you the length of the substring you want to extract.
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