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

Get Substring between two characters in SQL Server query

I want to get the string between two characters in the following string:

hello @user1, how are you?

I want to get the text between the @ and the SPACE after the @ which results in user1, is there a way to do this? There could even be 2 or more @ which I will need to extract like

hello @user1 ,@user2 ,@... , how are you?

here is a table-like example:

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

Sample Excpected Output
Hello @user1 and @user2 how are you? user1, user2
@user1 and @user2 replied user1, user2

but there will always be a SPACE after each @.

Thanks for the help.

>Solution :

The usual way to approach would be a combination of String_Split() and String_Agg():

with sampledata as (
  select 'Hello @user1 and @user2 how are you?' sample union all
  select '@user1 and @user2 replied'
)
select sample, String_Agg(Replace([value], '@',''), ', ') Result
from sampledata
cross apply String_Split(sample,' ')
where [value] like '@%'
group by sample;

See Working fiddle

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