I have a text column that contains values like CN-CHGO-BNSF
.
I need to reverse the order of the segments between hyphens. So the example above would be converted to BNSF-CHGO-CN
. I can easily do this in C# code, but here I could optimize my task if I could do it within a query.
Is there any way to do this in a SQL query? I'm using Entity Framework and SQL Server. Is this possible?
The number of segments will be one or more. (The number of hyphens will be zero or more.)
Examples
Input | Output |
---|---|
BNSF | BNSF |
CHGO-BNSF | BNSF-CHGO |
CN-CHGO-BNSF | BNSF-CHGO-CN |
FXE-EAGPA-BNSF-ROBSP-(RVPR) | (RVPR)-ROBSP-BNSF-EAGPA-FXE |
With SQL Server 2022, it looks like
EDIT Using String_AGG
Select A.*
,B.NewValue
From @YourTable A
Cross Apply ( Select NewValue = string_agg(value,'-') within group (ORDER BY convert(int,[key]) desc)
from openjson( '["' replace(string_escape(SomeCol,'json'),'-','","') '"]' )
) B