Skip to content
Advertisement

Get Substring between two characters in SQL Server query

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

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

here is a table-like example:

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.

Advertisement

Answer

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

See Working fiddle

As requested, a possible alternative approach to ensure the ordering of the string elements is as follows; this method uses a json array that provides the array index for ordering:

Note from this alternative Fiddle you can reverse the ordering or the strings using the desc keyword.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement