SQL Server Line Constructor or version of ST_MakeLine(pt1,pt2)?

Posted on

Question :

PostGIS provides a function called ST_MakeLine(pt1,pt2). It’s great for constructing lines. MySQL does the same with LineString(pt1,pt2). What do you call the SQL Server analog that takes two Points and constructs a LineString?

I looked up LineString, but didn’t see it mentioned.

Here is a test case on dbfiddle.

Sample data,

CREATE TABLE #tmp (
  pt1 geometry,
  pt2 geometry,
);

INSERT INTO #tmp(pt1,pt2) VALUES
  (geometry::Point(1,1,4326), geometry::Point(2,2,4326)),
  (geometry::Point(2,2,4326), geometry::Point(5,5,4326)),
  (geometry::Point(3,3,4326), geometry::Point(4,4,4326)),
  (geometry::Point(4,4,4326), geometry::Point(3,3,4326)),
  (geometry::Point(5,5,4326), geometry::Point(4,4,4326));

Query

SELECT pt1, pt2
  'My Line' AS line -- what goes here
FROM #tmp;

And I’m wanting “My Line” to be the LineString.

pt1         pt2         line
POINT (1 1) POINT (2 2) My Line
POINT (2 2) POINT (5 5) My Line
POINT (3 3) POINT (4 4) My Line
POINT (4 4) POINT (3 3) My Line
POINT (5 5) POINT (4 4) My Line

Answer :

Try ShortestLineTo():

SELECT
  pt1.ToString(),
  pt2.ToString(),
  pt1.ShortestLineTo(pt2).ToString() AS line -- what goes here
FROM #tmp;

Returns

POINT (1 1)   POINT (2 2)   LINESTRING (1 1, 2 2)
POINT (2 2)   POINT (5 5)   LINESTRING (2 2, 5 5)
POINT (3 3)   POINT (4 4)   LINESTRING (3 3, 4 4)
POINT (4 4)   POINT (3 3)   LINESTRING (4 4, 3 3)
POINT (5 5)   POINT (4 4)   LINESTRING (5 5, 4 4)

Leave a Reply

Your email address will not be published. Required fields are marked *