Geometry (Transact‑SQL)
The geometry data type stores planar (Euclidean) spatial data. It provides a rich set of methods for creating, analyzing, and manipulating geometric shapes such as points, lines, polygons, and collections.
Unlike geography, geometry does not account for the Earth's curvature, making it ideal for engineering, CAD, and map‑based applications that operate on flat surfaces.
Properties
| Property | Return Type | Description |
|---|---|---|
STArea() | float | Returns the area of the geometry instance. |
STLength() | float | Returns the total length of the geometry's boundary. |
STGeometryType() | nvarchar(30) | Returns the type of geometry (e.g., POINT, LINESTRING, POLYGON). |
STSpatialReferenceId | int | Spatial reference identifier (SRID) of the geometry. |
Methods
STIntersects(@g2)– Returns 1 if the two geometries intersect.STIntersection(@g2)– Returns the geometric intersection of two geometries.STBuffer(@distance)– Returns a geometry representing all points within the given distance of the original geometry.STContains(@g2)– Returns 1 if the instance completely contains the other geometry.STAsText()– Returns the Well‑Known Text (WKT) representation.STAsBinary()– Returns the Well‑Known Binary (WKB) representation.
Examples
Creating a Polygon
DECLARE @poly geometry = geometry::STPolyFromText(
'POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))', 0);
SELECT @poly.STArea() AS Area;
Finding Intersections
DECLARE @g1 geometry = geometry::STGeomFromText('POINT(5 5)', 0);
DECLARE @g2 geometry = geometry::STPolyFromText(
'POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))', 0);
SELECT @g1.STIntersects(@g2) AS Intersects,
@g1.STDistance(@g2) AS Distance;
Buffering a Geometry
DECLARE @line geometry = geometry::STGeomFromText('LINESTRING(1 1, 5 1)', 0);
SELECT @line.STBuffer(2).STAsText() AS BufferWKT;