Skip to content

Instantly share code, notes, and snippets.

@mjswart-d2l
Last active June 10, 2025 20:58
Show Gist options
  • Select an option

  • Save mjswart-d2l/3fa24bf5a50fab039a707eeb3f620782 to your computer and use it in GitHub Desktop.

Select an option

Save mjswart-d2l/3fa24bf5a50fab039a707eeb3f620782 to your computer and use it in GitHub Desktop.
DECLARE @StringAgg VARCHAR(1000);
DECLARE @LastStation VARCHAR(50);
SELECT @StringAgg = STRING_AGG(StationName, ''),
@LastStation = MAX(StationName)
FROM dbo.Stations;
SELECT
@StringAgg = STUFF(
@StringAgg,
CHARINDEX(StationFromName, @StringAgg) + 1,
CHARINDEX(StationToName, @StringAgg) - CHARINDEX(StationFromName, @StringAgg) - 1,
'')
+ SUBSTRING(
@StringAgg,
CHARINDEX(StationFromName, @StringAgg) + 1,
CHARINDEX(StationToName, @StringAgg) - CHARINDEX(StationFromName, @StringAgg) - 1)
FROM dbo.StationRoutingOverride
SELECT SUBSTRING(@StringAgg, N.value, 1) AS StationName
FROM generate_series(1, CHARINDEX(@LastStation, @StringAgg)) N
/*
StationName
-----------
A
B
I
D
E
S
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment