I would definitely try to do this on the server - try not to drag 400'000 lines to calculate one number (at the end).
: , . - SQL Server - .
- - , . CTE (Common Table Expression), 0.0, , (x + 1) x .
CTE, , .
CTE - :
;WITH Waypoints AS
(
SELECT
WaypointID, PrevWaypointID, Long, Lat, 0.0 as Distance, 0.0 as SumOfDistance
FROM
dbo.Waypoint
WHERE
PrevWaypointID IS NULL
UNION
SELECT
WaypointID, Long, Lat,
dbo.GetDistanceBetween(wp.WaypointID, pts.WaypointID),
pts.SumOfDistance + dbo.GetDistanceBetween(wp.WaypointID, pts.WaypointID)
FROM
dbo.Waypoint wp
INNER JOIN
Waypoints pts ON wp.PrevWaypointID = pts.WaypointID
WHERE
(some condition; ID = 1 or PreviousWaypointID IS NULL or something)
)
SELECT * FROM Waypoints