Creating a geography polyline from points in T-SQL

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 is as follows:

enter image description here

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

+4
source share
1 answer

try the following: ( note : arranging points is important for the proper generation of the line.)

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
+4
source

Source: https://habr.com/ru/post/1544873/


All Articles