HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

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

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
linesqlversionpt1pt2constructorserverst_makeline

Problem

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

Solution

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)

Code Snippets

SELECT
  pt1.ToString(),
  pt2.ToString(),
  pt1.ShortestLineTo(pt2).ToString() AS line -- what goes here
FROM #tmp;
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)

Context

StackExchange Database Administrators Q#188254, answer score: 8

Revisions (0)

No revisions yet.