5

I have a table schema that looks like this:

CREATE TABLE [dbo].[LongAndLats](
[Longitude] [decimal](9, 6) NULL,
[Latitude] [decimal](9, 6) NULL,
[SortOrder] [int] NULL
)

Sample data looks like this:

enter image description here

How can I convert these points into a geography polyline using TSQL?

1 Answer 1

5

try this: (note: the ordering of the points is important for the line to be generated correctly.)

DECLARE @BuildString NVARCHAR(MAX)
SELECT @BuildString = COALESCE(@BuildString + ',', '') + CAST([Longitude] AS NVARCHAR(50)) + ' ' + CAST([Latitude] AS NVARCHAR(50))
FROM dbo.LongAndLats
ORDER BY SortOrder             

SET @BuildString = 'LINESTRING(' + @BuildString + ')';   
DECLARE @LineFromPoints geography = geography::STLineFromText(@BuildString, 4326);
SELECT @LineFromPoints
3
  • I suggest to avoid SELECT @var = @var + '' ... ORDER BY ... construct. Group by value and create geography polyline from points Jan 13, 2018 at 17:38
  • 1
    @lad2025 Good point. That link says applying a function or expression to the columns in the SELECT list *should* produce deterministic behavior (as in the answer), they also go on to say The correct behavior for an aggregate concatenation query is undefined. The alternative constructs in your answer here, based on a similar question are more reliable. Thanks for the comment.
    – g2server
    Jan 13, 2018 at 21:04
  • String aggregation using COALESCE is apparently not safe: marc.durdin.net/2015/07/…
    – mikeck
    Jul 6, 2021 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.