0% found this document useful (0 votes)
14 views

Working with SQL Server Spatial - Workshop

Training Manual SQL Server

Uploaded by

nasiralimengal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Working with SQL Server Spatial - Workshop

Training Manual SQL Server

Uploaded by

nasiralimengal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

GeoMedia 2015

Working with SQL Server Spatial


Chuck Woodbury
Senior Consultant – Technology Services
Agenda

• SQL Server overview


• Spatial indexing and analysis
– Lesson 1: Working with Spatial tables
• Database Creation
• SQL Server Coordinate Systems
• DDL Operations
– Lesson 2: Spatial Queries, Indexing, and Analysis
• Loading Native Spatial Test Data
• Querying Geometry Components
• Creating Spatial Indexes
• Analyzing Spatial Data
• Using GeoMedia
• Tools and Utilities
– Lesson 3: Using GeoMedia
• Information only: Comparison with Oracle.

2
SQL Server Requirements

Supported Versions
• SQL Server 2008 R2 – Minimum required version (no arc support)
• SQL Server 2012 Std and Express – Fully supported
• SQL Server 2014 Std and Express – Fully supported

For Production
• Use a 64 bit server with plenty of memory and processing power.
• Use SQL Server 2012 or later.

3
SQL Server Spatial Data Types

Geography Geometry

So what's the difference?

• Geography types use Spherical calculations and utilize the earth's curvature
• Geometry types use Cartesian calculations and curvature is ignored

For relatively small areas they are roughly equivalent, but for large regions, using earth
curvature is important.

4
Geographic Spatial Models

GEOGRAPHY
• Planets are not flat and this is an inherent
problem when describing a location on a
planetary scale.

Uses
• Defining geographical features defined by long/lat
coordinates.
• Defining features that must take into account
earth curvature
• Measuring distance that must take into account
great circles and trajectories.
• Used anywhere the distortion inherent in
projected models create unacceptable
inaccuracies.

5
Projected Spatial Models

GEOMETRY
• While a geodetic model is the most accurate
way to represent geographic features, it is
difficult to use when you have to utilize flat
maps.
• Flat (projected) maps are still the most
common way to use location based data and
are much easier to work with.

Uses
• Regional maps
• City Maps
• Any large scale maps
• Floor plans
• Schematics

6
Key Data Type Differences

Property GEOMETRY GEOGRAPHY


Shape of Earth Flat Round
Coordinate System Projected Geographic
Coordinate Values Cartesian Latitude/Longitude
Unit of Measure Same as Coordinate Defined in
Values sys.spatial_reference_systems

SRID Not enforced Strictly enforced


Default SRID 0 4326 (WGS84)
Size limit None < one hemisphere
Ring Orientation Not significant Significant

7
Projected versus Geographic

Measurements
• Projected (GEOMETRY):
– measurements of distances and areas
are given in the same unit of
measurement as coordinates.
– the distance between (2, 2) and (5, 6)
is 5 units, regardless of the units used.
• Ellipsoidal (GEOGRAPHY):
– coordinates are given in degrees of
latitude and longitude.
– lengths and areas are usually
measured in meters and square
meters,
– measurement may depend on the
spatial reference identifier (SRID)
– most common unit of measurement is
meters using a reference identifier of
4326.

8
Projected versus Geographic

Orientation
 Projected (GEOMETRY):
– ring ordering is not enforced
– the ring orientation of a polygon is not
an important factor.
– a polygon described by ((0, 0), (10, 0),
(0, 20), (0, 0)) is the same as polygon
((0, 0), (0, 20), (10, 0), (0, 0)).
 Ellipsoidal (GEOGRAPHY):
– ring ordering is enforced
– a polygon is ambiguous without
orientation. Why?
– For example, does a ring around the
equator describe the northern or
southern hemisphere?
– the orientation of the outer ring (outside
boundary) is required to be counter-
clockwise.

9
Choosing the Right Spatial Data Type
Consistency
• You cannot combine geometry and geography data in the same query
• You cannot combine data using different SRIDs in the same query
• Be consistent in your schema, use the same projection and data type.
Accuracy/Size of model
• Geographic models are more accurate particularly for very large areas like
continents and large countries.
• Projected models are fine for smaller areas, like cities, states, small countries.
Mode of Presentation
• Geographic models have to be projected in order to be displayed. This can
introduce distortion into the model.
• Projected models are ready to display as is and no further distortion is introduced.
Performance
• Geographic models are slower with distance, length and area calculations (uses
spherical computations). The types of spatial analysis available is restricted.
• This is not an issue with Cartesian models.
Standards Compliance
• The geometry data type conforms to all OGC standards.
• The geography data type implements many of the same methods as the geometry
type but does not completely conform to OGC standards.

10
Types of Spatial Data

• 11 spatial data object types are supported


• 10 are instantiable; you can create and work with these instances in the
database.
• Each instance derives properties from their parent data types that distinguish
them as Points, LineStrings, Polygons, or GeometryCollections.

Note: Added in SQL Server 2012 and expanded to full globe in 2014.

11
Geometry and Geography Differences

• How connecting edges are defined


– The defining data for LineString and Polygon types are vertices only.
– The connecting edge between two vertices in a geometry type is a straight line.
– The connecting edge between two vertices in a geography type is a short great elliptic arc between the two vertices.
– A great ellipse is the intersection of the ellipsoid with a plane through its center and a great elliptic arc is an arc segment on the
great ellipse.

• How circular arc segments are defined


– Circular arc segments for geometry types are defined on the XY Cartesian coordinate plane (Z values are ignored).
– Circular arc segments for geography types are defined by curve segments on a reference sphere.
– Any parallel on the reference sphere can be defined by two complementary circular arcs where the points for both arcs have a
constant latitude angle.

• Measurements in spatial data types


– In the planar, or flat-earth, system, measurements of distances and areas are given in the same unit of measurement as
coordinates. Using the geometry data type, the distance between (2, 2) and (5, 6) is 5 units, regardless of the units used.
– In the ellipsoidal, or round-earth system, coordinates are given in degrees of latitude and longitude. However, lengths and
areas are usually measured in meters and square meters, though the measurement may depend on the spatial reference
identifier (SRID) of the geography instance. The most common unit of measurement for the geography data type is meters.

• Orientation of spatial data


– In the planar system, the ring orientation of a polygon is not an important factor. For example, a polygon described by ((0, 0),
(10, 0), (0, 20), (0, 0)) is the same as a polygon described by ((0, 0), (0, 20), (10, 0), (0, 0)). The OGC Simple Features for SQL
Specification does not dictate a ring ordering, and SQL Server does not enforce ring ordering.
Spatial Reference Systems (SRID’s)

SQL Server uses the EPSG (European Petroleum Survey Group)


Standard for coordinate system references:

• GEOMETRY
– An SRID is not required to perform calculations, the geometry resides in
planar space
– SRID = 0 by default, there are no projected SRID's in SQL Server

• GEOGRAPHY
– An SRID is required (just like Oracle) and must match one of the
geographic EPSG SRID’s already stored in SQL Server
– SRID = 4326 by default (WGS 84)

Note: The SRID is required, it cannot be NULL!

13
More on SRIDs…

• SQL Server stores the details of all supported geodetic EPSG


coordinate systems in the following table:
select * from sys.spatial_reference_systems

• If an SRID is not listed, it is not supported. Since projected data does


not require an SRID, projected SRIDs are not included.
• Spatial references are stored in WKT format, for example:
select well_known_text
from sys.spatial_reference_systems
where authority_name='EPSG'
and authorized_spatial_reference_id=4326
returns
GEOGCS["WGS 84",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84", 6378137, 298.257223563]],
PRIMEM["Greenwich", 0],
UNIT["Degree", 0.0174532925199433]]

14
Storage Tolerance

Coordinate values are stored as floating point binary


• Spatial calculations use integer arithmetic (integer based topology)
• Coordinate values are NOT converted to integers, they are snapped to
the closest integer value on a dynamically-scaled integer based grid.
• SQL Server 2008 uses a 27 bit grid
• SQL Server 2012 and later uses a 48 bit grid to improve accuracy

Calculation error is determined by geometry scale


• The greater the range of coordinate values, the more coarse the grid
resolution
• As an example in geographic, calculations on a line 10000 km long can
be off by as much as 10 cm.
• This is not generally an issue in projected data covering smaller areas.

15
Precisions and Limits on Storage

Storage Precision
• Each coordinate uses 8 bytes (binary double-precision floating-point)
• Roughly equates to 15 digits of precision
• Any extra precision is ignored, and coordinates with less precision will still use
8 bytes. For Example:
21.565 uses just as much space as 21.56547898754213354258874411255112 or
21.565000000000000 and 21.565478987542134 respectively.

Limits
• The overhead per row is 6 bytes (1 reserved, 1 for the endian, 4 for the type)
• A single geometry is limited at 2 GB per row of data
• Point geometry defined with only 2 coordinates uses 22 bytes (16 + 6)
• A linestring containing a minimum of 4 coordinates uses 38 bytes (32 + 6)
• For polygons, it depends on the number of points.

The DATALENGTH function can tell you how much space is used by a individual row:

SELECT DATALENGTH(geometry) FROM [dbo].[Counties];

16
So how much data can actually be stored?

Each row can contain roughly:

• 134 million 2D vertices


• 89 million 3D vertices

In other words, there is no practical limit. It would be rare for a


single row of data to require this many vertices.

Compare this to Oracle's SDO_GEOMETRY limit of:

• 2D vertices: 524288
• 3D vertices: 349525

NOTE: SQL Server spatial can store more vertices, but it still has to retrieve
them. You also have to consider spatial processing times on data that is this
large. The performance would be poor!

17
Working with spatial data

If spatial data is stored as binary double precision, how do you access it?
• Using direct conversion to/from geometry/geography data type to both
WKT and WKB formats:
– Well-known text (WKT) is a text markup language for representing vector geometry
objects on a map, spatial reference systems of spatial objects and transformations
between spatial reference systems.
– Well-known binary (WKB) is the binary equivalent used to transfer and store the
same information on databases
• These formats are regulated by the Open Geospatial Consortium
(OGC) and described in their Simple Feature Access and Coordinate
Transformation Service specifications

http://www.opengeospatial.org/

18
WKT (Well Known Text)

Coordinates for geometries may be:


– 2D (x, y)
– 3D (x, y, z),
– 4D (x, y, z, m) with an m value that is part of a linear referencing
– Empty geometries can be specified by using the symbol EMPTY

19
SQL Server 2012 Adds WKT support for curves (arcs)

• CircularString – Three point based circular arcs, or curves basic subtype, corresponding to a
LineString for linear data. Three points are used to define a segment with the start (first point) and end
(third point) points and another point (second point) anywhere along the circular arc.

CIRCULARSTRING(0 -23.43778, 0 0, 0 23.43778)

• CompoundCurve – Compound curves enable you to define new curves that can be composed of
circular strings only, or circular strings and linear strings.

COMPOUNDCURVE(
CIRCULARSTRING(0 -23.43778, 0 0, 0 23.43778),
CIRCULARSTRING(0 23.43778, -45 23.43778, -90 23.43778))

• CurvePolygon - Curve polygons are similar to polygons, having at least one ring and zero or more
holes (inner rings). Curve polygons are composed of linear strings, circular strings, and/or compound
curves.

CURVEPOLYGON(
COMPOUNDCURVE(
(0 -23.43778, 0 23.43778),
CIRCULARSTRING(0 23.43778, -45 23.43778, -90 23.43778),
(-90 23.43778, -90 -23.43778),
CIRCULARSTRING(-90 -23.43778, -45 -23.43778, 0 -23.43778)
)

20
WKB (Well known binary)

• Well-known binary (WKB) is represented as hexadecimal


strings.
• The first byte indicates the byte order for the data:
– 00 : big endian
– 01 : little endian
• The second part is an integer for the geometry type, as
described at right:
• For example, POINT(2.0 4.0) is represented as:

000000000140000000000000004010000000000000,
where:
– 1-byte integer 00 or 0: big endian
– 4-byte integer 00000001 or 1 POINT (2D)

– 8-byte float 4000000000000000 or 2.0: x-coordinate


– 8-byte float 4010000000000000 or 4.0: y-coordinate

21
WKT/WKB conversions

STGeomFromText
Returns a geometry or geography instance from the WKT representation augmented
by any elevation or measure values.
STGeomFromWKB
Returns a geometry or geography instance from the WKB representation augmented
by any elevation or measure values.

Formats
datatype::method()
or
geometry::STGeomFromText('geometry_tagged_text',SRID)
geometry::STGeomFromWKB('WKB_geometry',SRID)

geography::STGeomFromText('geometry_tagged_text',SRID)
geography::STGeomFromWKB('WKB_geometry',SRID)

Examples
geometry::STGeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0)
geography::STGeomFromText('LINESTRING(-122.360 47.656,-122.343 47.656)',4326)

DECLARE @g geometry;
SET @g = geometry::STGeomFromText('POINT(100 100)', 0);
SELECT @g.ToString();

DECLARE @g geometry;
SET @g = geometry::STGeomFromWKB(0x010100000000000000000059400000000000005940, 0);
SELECT @g.STAsText();

22
Spatial Table Requirements

Clustered Primary keys


• Clustered Primary key is required
– A clustered index determines the physical order of data in a table
and a table can contain only one clustered index
– Primary key indexes are automatically clustered if no other
clustered index exists
• Primary keys can be based on one of more columns (up to
16) and can be of any non-spatial data type
Best Practices
• Use a single identity based clustered key column
• Geometries are retrieved using the key value, this is more
efficient with a single key column value.

23
DDL Operations

Example DDL for a simple table


New:
CREATE TABLE [dbo].[MyGeometryTable](
[id] INT IDENTITY (1,1) PRIMARY KEY,
[SpatialDataCol] GEOMETRY);

Or

CREATE TABLE [dbo].[MyGeographyTable](


[id] INT IDENTITY (1,1) PRIMARY KEY,
[SpatialDataCol] GEOGRAPHY);

Existing:
ALTER TABLE MyGeometryTable
ADD SpatialDataCol GEOMETRY);

Or

ALTER TABLE MyGeographyTable


ADD SpatialDataCol GEOGRAPHY);

Note: Clustered primary keys are required for tables containing spatial data types. For best
results and performance, use an identity key.

24
DML Operations – Inserts using WKT

Use the Static Methods for either WKT or WKB


STGeomFromText : accepts any of the seven spatial data objects - POINT, POLYGON,
LINESTRING, MULTIPOINT, MULTIPOLYGON, MULTILINESTRING and
GEOMETRYCOLLECTION.
geometry::STGeomFromText('geometry_tagged_text',SRID)
geography::STGeomFromText('geometry_tagged_text',SRID)
You can also force the use of a specific type by calling a specific sub method, if an incorrect geometry type is
passed, the result will be a Framework error exception:

• STPointFromText - only accepts the Latitude/Easting and Longitude/Northing coordinates of a


point in that order.
• STLineFromText - only accepts linear coordinates
• STPolyFromText - only accepts polygon coordinates
• STMPointFromText - only accepts multi-point coordinates
• STMLineFromText - only accepts multi-line coordinates
• STMPolyFromText - only accepts multi-polygon coordinates
• STGeomCollFromText - only accepts geometry collection coordinates
• Parse - equivalent to STGeomFromText but assumes the SRID = 0
• Null - loads a null geometry or geography instance
• Point - constructs a 2D point from an X, Y, SRID value.

Why is an SRID required if its supposed to be zero anyway?

25
DML Operations – Inserts using WKB

For WKB:
STGeomFromWKB : accepts any of the seven spatial data objects - POINT,
POLYGON, LINESTRING, MULTIPOINT, MULTIPOLYGON, MULTILINESTRING and
GEOMETRYCOLLECTION.
geometry::STGeomFromWKB(WKB*, SRID)
geography::STGeomFromWKB(WKB*,SRID)

* WKB is a varbinary(max) expression.

You can also force the use of a specific type by calling a specific sub method:
• STPointFromWKB - only accepts the Latitude/Easting and Longitude/Northing
coordinates of a point in that order.
• STLineFromWKB - only accepts linear coordinates
• STPolyFromWKB - only accepts polygon coordinates
• STMPointFromWKB - only accepts multi-point coordinates
• STMLineFromWKB - only accepts multi-line coordinates
• STMPolyFromWKB - only accepts multi-polygon coordinates
• STGeomCollFromWKB - only accepts geometry collection coordinates
• Parse - equivalent to STGeomFromWKB but assumes the SRID = 4326
• Null - loads a null geometry or geography instance
• Point - constructs a 2D point from an lat, long, SRID value.

26
DML Operations – Geometry Inserts using WKT

Inserting Geometry
INSERT INTO MyPointTable(GeometryCol)
VALUES (geometry::STPointFromText('POINT (100 100)', 0));
INSERT INTO MyLineTable(GeometryCol)
VALUES (geometry::STLineFromText('LINESTRING (100 100, 20 100, 220 180)', 0));
INSERT INTO MyPolyTable(GeomCol1)
VALUES (geometry::STPolyFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0));

or for 3D
INSERT INTO MyPointTable(GeometryCol)
VALUES (geometry::STPointFromText('POINT (100 100 30)', 0));
INSERT INTO MyLineTable(GeometryCol)
VALUES (geometry::STLineFromText('LINESTRING (100 100 5, 20 100 10, 220 180 15)', 0));
INSERT INTO MyPolyTable(GeomCol1)
VALUES (geometry::STPolyFromText('POLYGON ((0 0 0, 150 0 10, 150 150 20, 0 150 30, 0 0
0))', 0));

Note:
• Coordinates are space delimited in X Y or X Y Z with vertices separated by commas.
• Polygons require double parenthesis (()) to delineate parts.
• SRID is always 0 for geometries. You could have used STGeomFromText for all of these as
well.

27
DML Operations – Geography Inserts using WKT

Inserting Geography (Longitude, Latitude)

INSERT INTO MyPointTable(GeographyCol)


VALUES (geography::STPointFromText('POINT (122.360 47.656)', 0));
INSERT INTO MyLineTable(GeographyCol)
VALUES (geography::STLineFromText('LINESTRING(-122.360 47.656, -122.343 47.656)',4326));
INSERT INTO MyPolyTable(GeographyCol)
VALUES (geography::STPolyFromText('POLYGON((-122.358 47.653, -122.348 47.649,-122.348
47.658, -122.358 47.658, -122.358 47.653))', 4326));

or for 3D

INSERT INTO MyPointTable(GeographyCol)


VALUES (geography::STPointFromText('POINT (122.360 47.656 560)', 0));
INSERT INTO MyLineTable(GeographyCol)
VALUES (geography::STLineFromText('LINESTRING(-122.360 47.656 120,
-122.343 47.656 350)',4326));
INSERT INTO MyPolyTable(GeographyCol)
VALUES (geography::STPolyFromText('POLYGON((-122.358 47.653 0, -122.348 47.649 10,
-122.348 47.658 10, -122.358 47.658 30,
-122.358 47.653 0))', 4326));
Note:
• SRID must be specified and cannot be 0.
• Coordinates are space delimited in Latitude Longitude with optional elevation.
• Vertices are separated by commas.
• Polygons require double parenthesis (()) to delineate parts.

28
DML Operations – Other insert examples

Using extended methods

INSERT INTO MyPointTable(GeographyCol)


VALUES (geography::POINT(-122.360, 47.656, 0));

INSERT INTO MyLineTable(GeographyCol)


VALUES (geometry::PARSE('LINESTRING(12236.0 4765.6, 12234.3 4765.8)');

INSERT INTO MyLineTable(GeographyCol)


VALUES (geography::PARSE('LINESTRING(-122.360 47.656 22, -122.343 47.656 44)');

INSERT INTO MyPolyTable(GeographyCol)


VALUES (geography::[NULL]);

• Point uses comma separated floating point values (2D only).


• Parse is just a shortcut and is mainly used with projected data (SRID is 0).
• NULL is useful if you need to insert an empty geometry or geography as a
placeholder.

29
DML Operations – Updates using WKT

Updates work like any other column updates, just use the type and
method for your specific data:

UPDATE MyGeometryTable SET GeometryCol =


(geometry::PARSE('LINESTRING (100 100, 20 180, 180 180)'))
WHERE ID = 12;

UPDATE MyGeographyTable SET GeographyCol =


(geography::STGeomFromText('LINESTRING (100 100, 20 180, 180
180)', 4326))
WHERE ID = 45;

UPDATE MyGeographyTable SET GeographyCol = (geography::[NULL])


WHERE ID = 33;

30
Table Constraints

Constraining coordinate systems


ALTER TABLE SpatialTable
ADD CONSTRAINT enforce_srid_geographycolumn
CHECK (SpatialCol.STSrid = 4326)

Constraining storage types


ALTER TABLE SpatialTable ADD CONSTRAINT SpatialGeomCheck CHECK
(SpatialCol.STGeometryType() = 'POINT')

31
Using TSQL

DECLARE @g geometry;
SET @g = geometry::Parse('LINESTRING (100 100, 20 180, 180 180)');
UPDATE MyGeometryTable SET GeometryCol = @g WHERE ID = 12;

DECLARE @g geometry;
SET @g = geometry::STPolyFromText('POLYGON ((5 5, 10 5, 10 10, 5 5))', 0);
SELECT @g.ToString();

DECLARE @g geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343
47.656)', 4326);
INSERT INTO MyPolyTable(GeographyCol) VALUES @g;

32
Converting geometry types back to WKT

For 2D WKT retrieval, use the following method:


.STAsText()

SELECT GeometryCol.STAsText()
FROM MyGeometryTable

But for full 2D, 3D, or M return, use one of these:


.ToString()
.AsTextZM

SELECT GeometryCol.ToString()
FROM MyGeometryTable;
SELECT GeometryCol.AsTextZM()
FROM MyGeometryTable;

These work with both geometry and geography types.

33
Query Operation Examples

Here are a some examples for a table called Cities with a PointGeometry
column:

SELECT [PointGeometry].STAsText() FROM


[dbo].[CITIES];

SELECT [PointGeometry].AsTextZM() FROM


[dbo].[CITIES];

34
Displaying Results Graphically

Query geometry columns directly


and visualize the results In SQL Server Management Studio

Select AREAGEOMETRY from STATES

Use UNION ALL to combine results


Select AREAGEOMETRY from STATES
union all
Select LINEARGEOMETRY from RIVERS
union all
SELECT PointGeometry FROM CITIES

35
Geometry Validation

Make sure your data is valid

.STIsValid () - SQL Server produces only valid geometry instances, but allows
for the storage and retrieval of invalid instances. This function will return a 0 is
the instance of the geometry is invalid. This function works for geography types
in SQL Server 2012.
.IsValidDetailed() - New in SQL Server 2012, this returns a message that can
help in identifying validity issues with a spatial object.
.MakeValid () - This function converts an invalid geometry instance into a
geometry instance with a valid Open Geospatial Consortium (OGC) type. This
method may cause a change in the type of the geometry instance, as well as
cause the points of a geometry instance to shift slightly. This function works for
geography types in SQL Server 2012.

Example
DECLARE @g geometry;
SET @g = geometry::STGeomFromText('LINESTRING(0 2, 1 1, 1 0, 1 1, 2 2)', 0);
SELECT @g.STIsValid();
Result: 0
SET @g = @g.MakeValid();
SELECT @g.STIsValid();
Result: 1
SELECT @g.ToString();
Result: MULTILINESTRING ((0 2, 1 1, 2 2), (1 1, 1 0))

36
Querying and Manipulations SRIDs

.STSrid - Return the SRID from a geometry or geography

Retrieving the SRID used

SELECT GEOM_POINT.STSrid FROM CitiesWGS

Make sure all the rows have the same SRID

SELECT Distinct(GEOM_POINT.STSrid) FROM [dbo].[CitiesWGS]

Updating an existing SRID

Update CitiesWGS SET GEOM_POINT.STSrid = 4326

37
Querying on information in a spatial column

Basic information
• Dimension
• geometry type
• number of geometries stored
• The methods for these include:
– .STDimension() - Return the dimension of the geometry instance (0 for
point, 1 for line, and 2 for polygon with -1 for any that are NULL). One
would argue that this is not really a dimension and more of a type.
– .STGeometryType() – Returns the geometry type
– .STNumGeometries() – Returns the number of geometries stored in the
column

Examples
SELECT DISTINCT(Geometry.STDimension() ) From Railways
SELECT DISTINCT(Geometry.STGeometryType() ) From Railways
SELECT Geometry.STNumGeometries() From Railways

38
Retrieving selected parts of a point geometry

Retrieving coordinates
• .STX - Return the X coordinate from a point geometry
SELECT GeometryCol.STX FROM MyGeometryTable
• .STY - Return the Y coordinate from a point geometry
SELECT GeometryCol.STY FROM MyGeometryTable
• .Long - Return the Longitude from a point geography
SELECT GeographyCol.Long FROM MyGeographyTable
• .Lat - Return the Latitude from a point geography
SELECT GeographyCol.Lat FROM MyGeographyTable
Retrieving elevation and measure values
• .Z - Return the elevation from a point geometry or geography
SELECT GeometryCol.Z FROM MyGeometryTable
SELECT GeographyCol.Z FROM MyGeographyTable
• .M - Return the measure from a point geometry or geography
SELECT GeometryCol.M FROM MyGeometryTable
SELECT GeographyCol.Z FROM MyGeographyTable

39
Retrieving selected parts of lines
For line strings, getting the start point and end point is easy:

• .STStartPoint() – Return the start point of the geometry/geography


• .STEndPoint() – Return the end point of the geometry/geography

SELECT Geometry.STStartPoint() AS STARTPT, Geometry.STEndPoint() as ENDPT


from Railways

but to get a point in between, you need to know the number of points that make
up the entire line:

• .STNumPoints() – Returns the number of points in the geometry/geography.


Duplicates are counted twice, connecting points between segments are only
counted once.
• .STPointN() – Return the N point of the geometry/geography

DECLARE @g geometry;
SET @g = geometry::STGeomFromText('LINESTRING(0 0, 2 2, 1 0)', 0);
SELECT @g.STPointN(2).ToString();

Result: POINT(2 2)

40
Retrieving selected parts of lines and polys

For multi geometry types, you may need to find out how many separate
geometries are stored and just retrieve one of them:

• .STNumGeometries ( ) - Returns the number of geometries that


comprise a geometry instance.
• .STGeometryN() – Returns the Nth geometry

Specific to polygon, you may need to return just the exterior ring or find
and return a specific interior ring:

• .STExteriorRing() – Returns just the exterior ring of a polygon


• .STNumInteriorRing() – Returns the number of interior geometries in a
polygon
• .STInteriorRingN() – Returns the Nth interior ring or a polygon

41
Length and Area Functions

.STArea() - Returns the total surface area of a geometry instance. If a point or line is used, the area will
be 0.

SELECT GEOMETRY.STArea() AS SQMeters FROM STATES WHERE STATE_NAME='Alabama'

.STLength() - If a geometry instance is closed, its length is calculated as the total length around the
instance; the length of any polygon is its perimeter and the length of a point is 0. The length of any
geometry collection type is the sum of the lengths of its contained geometry instances.

SELECT GEOMETRY.STLength() AS Perimeter FROM STATES WHERE STATE_NAME='Alabama'

Note: Results for geography are always returned in meters, otherwise the result is
based on unit of storage.

42
Spatial Indexing in SQL Server

• A spatial index is defined on a table column that contains spatial data (a spatial
column). Each spatial index refers to a finite space. For example, an index for a
geometry column refers to a user-specified rectangular area on a plane.
• Spatial indexes are not required, but performance will be poor without them.
• The index-creation process decomposes the space into a four-level grid
hierarchy. These levels are referred to as level 1 (the top level), level 2, level 3,
and level 4.
• Each successive level further decomposes the level above it, so each upper-
level cell contains a complete grid at the next level. Decomposition is
independent of any unit if measurement .

43
Spatial Indexing: Bounding Box

Bounding Box
• GEOMETRY based indexes require a bounding rectangle to confine the grid
decomposition. The bounding box is defined by four coordinates, (x-min,y-
min) and (x-max,y-max), which are stored as properties of the spatial index.
• GEOGRAPHY based indexes use a bounding box implicitly defined in the
hemisphere projection.

Note: In SQL Server 2012, the optimal bounding box is generated automatically during indexing.

44
OK, here's just the basics:
• The bounding box is broken up into a grid of cells.
• Each feature is evaluated to see which cells in the grid it intersects with.
• The index contains the list of cells along with the primary key of the row containing
the feature.
• Comparing two features is a matter of comparing the list of grid cells - if there are
no matching cells, the spatial values do not intersect and there's no need to do the
expensive intersection calculation.

• Spatial query performance is dependent on the efficiency of the spatial index.


• Only operations computed on objects that are entirely inside of the bounding box
benefit from the spatial index but it is not necessary for all data to be included in
the bounding box.
• If the data distribution is highly skewed, you can get better performance if the
bounding box is located where the majority of your data is. Outliers will still be
included in the query results but a small number of outliers will not affect
performance.

45
Spatial Indexing Restrictions

• These can only be used on columns of type GEOMETRY or GEOGRAPHY.


• Table requires a primary key and you can have a max of 15 columns defined
as a composite primary key.
• For best results use a single identity based clustered primary key.
• The maximum size of individual index key records is 895 bytes. Larger sizes
raise an error.
• Spatial Indexes cannot be specified on indexed views.
• You can have up to 249 spatial indexes on any spatial column. Creating more
than one spatial index on the same spatial column can be useful, for example,
to index different tessellation parameters in a single column.
• Primary Key column cannot be changed unless spatial index is dropped.

46
Spatial Indexing Syntax

Simple Syntax

CREATE SPATIAL INDEX MyTable_SIDX ON MyTable(geometry_col)


WITH ( BOUNDING_BOX = ( 0, 0, 500, 200 ) );

CREATE SPATIAL INDEX MyTable_SIDX ON MyTable(geography_col);

Or a little more complex:

CREATE SPATIAL INDEX MyTable_SIDX ON MyTable(geometry_col)


USING GEOMETRY_GRID
WITH (BOUNDING_BOX = ( xmin=0, ymin=0, xmax=500, ymax=200 ),
GRIDS = (LOW, LOW, MEDIUM, HIGH),
CELLS_PER_OBJECT = 64, PAD_INDEX = ON );

CREATE SPATIAL INDEX MyTable_SIDX ON MyTable(geography_col)


USING GEOGRAPHY_GRID
WITH (GRIDS = (LOW, LOW, MEDIUM, HIGH),
CELLS_PER_OBJECT = 64, PAD_INDEX = ON );

47
Spatial Indexing Syntax in SQL Server 2012 and later

Autogrid
• A new auto grid spatial index is available for both spatial types (geometry_auto_grid and
geography_auto_grid).
• The GRIDS parameter is no longer valid or needed when this index type is used. The new auto grid
actually uses a different strategy to pick the right tradeoff between performance and efficiency.
• It uses eight levels (instead of four) for better approximation of objects of various sizes.
• For example:

CREATE SPATIAL INDEX idxGeog ON table(column)


USING GEOGRAPHY_AUTO_GRID;
Compression
• Compression can be enabled on spatial indexes with Transact-SQL DDL:

CREATE SPATIAL INDEX idxGeom ON table(column)


USING GEOGRAPHY_GRID
WITH (DATA_COMPRESSION = page|row);
• Spatial indexes with compression are 40-50 percent smaller, with a 5-10 percent performance
overhead.

48
Creating a Spatial Index Using Management Studio

• If you are SQL challenged you can create and modify spatial indexes
via the SQL Server Management Studio.
• Select the table containing a geometry/geography based column, right
click on Indexes, select New Index and then pick Spatial Index.
• You can also Rebuild spatial indexes from here.

49
Spatial Analysis: GEOMETRY METHODS

geometry1.method_name(geometry2) operator valid_number

• geometry1.STContains (geometry2) = 1 (1 for TRUE, 0 for FALSE)


• geometry1.STDistance (geometry2) < number or <= number
• geometry1.STEquals (geometry2) = 1
• geometry1.STIntersects(geometry2) = 1
• geometry1.STOverlaps (geometry2) = 1
• geometry1.STTouches (geometry2) = 1
• geometry1.STWithin (geometry2) = 1
• geometry1.STCrosses (geometry2) = 1
• geometry1.STDisjoint (geometry2) = 1
• geometry1.Filter (geometry2) = 1

Example: Find all the Cities contained by the State Alabama.


SELECT * FROM Cities A, States B
WHERE B.State_Name = 'Alabama'
AND B.AreaGeometry.STContains(A.PointGeometry)=1;

Note: No Coordinate conversion is performed so SRID’s in geometry1 must match those used in
geometry2. If there is a mismatch, the result will be NULL. This not generally an issue with the geometry
data type but be careful with geography.

50
Spatial Analysis: GEOGRAPHY METHODS

geography.method_name(geography) operator valid_number

• geography1.STIntersects (geography2) = 1 (1 for TRUE, 0 for FALSE)


• geography1.STEquals (geography2) = 1
• geography1.STDistance (geography2) < number or <= number
• geography1.STDisjoint (geography2) = 1
• Geography1.Filter (geography2) = 1

There are fewer comparison methods available with geographic data but support for
STWithin(), STContains(), and STOverlaps() were all added in SQL Server 2012.

For example, find all the Cities within 10KM of Lake Michigan:

SELECT * FROM Cities A, Lakes B


WHERE B.Name = 'Lake Michigan'
AND A.City_Location.STDistance(B.Lake_Area)<10000

Note: No Coordinate conversion is performed so SRID’s in geography1 must match


those used in geography2. If there is a mismatch, the result will be NULL.

51
Analysis Functions

These functions all return a geometry or geography:


• .STBoundary() – Returns just the linestring boundary of a geometry instance.

SELECT Geometry.STBoundary() FROM STATES where state_name='Alabama'


SELECT Geometry.STBoundary().STAsText() FROM STATES where state_name='Alabama'
MULTILINESTRING ((765141.43094969285 -780164.55909799982, 770067.8002468663…

• .STBuffer(distance) - Returns a geometric object that represents the union of all


points whose distance from a geometry instance is less than or equal to a specified
value.

SELECT Geometry.STBuffer(10000) FROM STATES where state_name= 'Alabama'

• .STDifference() – Returns point set from one geometry instance that does not lie
within another geometry instance.

SELECT A.Geometry.STDifference(b.Geometry_Native)
FROM STATES A, COUNTIES B
WHERE A.state_name=B.State_name
AND A.state_name='Alabama'
AND B.County_Name='Morgan'

52
Analysis Functions (cont)

• .STSymDifference() - Returns an object that represents all


points that are either in one geometry instance or another
geometry instance, but not those points that lie in both
instances.
SELECT A.Geometry.STSymDifference(B.Geometry)
FROM STATES A, COAL_FIELDS B
WHERE A.state_name='Alabama'

• .STIntersection() - Returns an object that represents the


points where a geometry instance intersects another
geometry instance.
SELECT A.Geometry.STIntersection(B.Geometry)
FROM STATES A, COAL_FIELDS B
WHERE A.state_name='Alabama'

• .STUnion() - Returns an object that represents the union of


a geometry instance with another geometry instance.
SELECT A.Geometry.STUnion(B.Geometry)
FROM STATES A, BAYS B
WHERE A.state_name='Alabama'
AND A.STATE_FIPS=B.STATE_FIPS

53
Analysis Functions (GEOMETRY ONLY)

These functions only return geometries:


• .STPointOnSurface() - Returns an arbitrary point located within the interior of
a geometry instance (polygons only).
SELECT Geometry.STPointOnSurface() FROM STATES
WHERE state_name='Alabama'

• .STCentroid() - Returns the geometric center of a geometry instance that


consists of one or more polygons.
SELECT Geometry.STCentroid() FROM STATES
WHERE state_name='Alabama'

• .STConvexHull() - Returns the smallest convex polygon that contains the


given geometry instance. Points or co-linear Line String instances will produce
an instance of the same type as that of the input. Geography support was
added in SQL Server 2012.
SELECT Geometry_NAtive.STConvexHull() FROM STATES

• .STEnvelope() - Returns the minimum axis-aligned bounding rectangle of the


instance.
SELECT Geometry_NAtive.STEnvelope() FROM STATES

54
Other geometry based functions

• .MakeValid() - Converts an invalid geometry instance into a geometry instance with a


valid OGC type. Works for geography in SQL Server 2012.
• .Reduce(tolerance) - Returns an approximation of the given geometry instance
produced by running an extension of the Douglas-Peucker algorithm on the instance
with the given tolerance.

SELECT Geometry_Native.Reduce(10000) FROM STATES


WHERE state_name='Alabama'

55
Additional Methods for Arcs in SQL Server 2012

• .BufferwithCurves(distance) - uses circular arcs to


construct buffered object with greatly reduced number of
points compared to .STBuffer().
• .STNumCurves() and .STCurveN() - are used for
iteration through the list of the circular arc edges.
• .STCurveToLine() and .CurveToLineWithTolerance() are
used for approximating circular arcs with line segments
within default and user specific tolerance.

56
Aggregate Methods in SQL Server 2012

• UnionAggregate() - combines multiple spatial objects into a single spatial


object, removing interior boundaries, where applicable:

SELECT Geography::UnionAggregate(geog) FROM Counties


WHERE name = 'Washington'

• EnvelopeAggregate - for the geography type returns a bounding circular


object as a CurvePolygon which encloses one or more spatial objects. For the
geometry type returns a 5 point polygon (rectangle) which encloses one or
more spatial objects.

SELECT Geometry::EnvelopeAggregate(geom) FROM Counties


WHERE name = 'Washington'

• CollectionAggregate - returns a geometry collection with one geometry part


for each spatial object(s) in the selection set.

SELECT Geography::CollectionAggregate(geog) FROM Counties


WHERE name = 'Washington';

• ConvexHullAggregate - returns a convex hull polygon which encloses one or


more spatial objects.
SELECT Geography::CpmvexHullAggregate(geog) FROM Counties
WHERE name = 'Washington';

57
Creating Spatial Views

• Views are just stored queries


• Spatial views are no different, any spatial query can be a view.
• No spatial indexes are required on the view, they are picked up from the base
data.
• The only requirement is that a key column be included in the view definition.

Simple View
CREATE VIEW Railway_noise_buffer AS
SELECT [ID1],[Name],[type] ,[Geometry].STBuffer(100)
FROM [Railways];

Join View
CREATE VIEW Sjaelland_Roads AS
SELECT a.ID1, a.Name, a.geometry
FROM Roads a, Denmark b
WHERE b.Name = 'SJAELLAND'
AND a.geometry.STWithin(b.geometry)=1

58
Lesson 1 and 2: Working with Spatial Tables

Lesson 1: Working with Spatial tables: Pages 6-9


• Database Creation
• SQL Server Coordinate Systems
• DDL Operations
Lesson 2: Spatial Queries, Indexing, and Analysis: Pages15-21
• Loading Native Spatial Test Data
• Querying Geometry Components
• Creating Spatial Indexes
• Analyzing Spatial Data

If you finish early, try to complete lesson 2, pages 21-25.


GeoMedia Spatial Data Server

• Delivered as an expansion pack for 2013 and 2014, now included in 2015
• Requires SQL Server 2008 R2 or later but you should be using SQL Server
2012 or 2014 if you want arc support.
• Read-Write capability for GeoMedia Professional and WebMap Professional
• Certified as Read-Only for GeoMedia, Viewer, and WebMap (RW capability is
there but may go away in the future).

• Not compatible with SQL Azure

60
Compatibility

• GeoMedia
• GeoMedia Viewer
• GeoMedia Fusion
• GeoMedia Parcel Manager
• GeoMedia Transportation Manager
• GeoMedia Transportation Analyst
• WebMap WebMap Pro
• WebMap Publisher
• Add-on applications not listed are not fully compatible with
this data server.
• AFM (Advanced Feature Model) enabled schemas are
also not compatible.

61
Known Issues

• The SQL Server Spatial data server is not a replacement


for the existing SQL Server data server:
– Queries, spatial filters, and other objects that are based on the
standard SQL Server data server and stored in a GeoMedia
Library will not be compatible with the new SQL Server Spatial
data server.
– Library content will have to be recreated using the new data server.
• WebMap based applications that attempt to use an ADO
connection to SQL Server Spatial that was stored in
metadata by the WebMap Publisher Administrator will fail.
– A GDO connection to SQL Server Spatial data will work correctly.
– There may be some functionality in WebMap/WebMap Publisher
that will fail to use the spatial filter capability in the SQL Server
Spatial data server.
• The data sever is not AFM data model compatible.

62
Metadata Requirements - GeoMedia

GM Metadata objects are required to use


SQL Server spatial data. These tell
GeoMedia how to use the data.
To create the required metadata objects,
use one of the following methods:
• Database Utilities
– Use the Create Metadata Tables
command.
– This is the preferred method and is
also the method to use when
updating the metadata objects as
new releases become available.
• Export to SQL Server
– The metadata.sql file generated by
Export to SQL Server can also be
run directly in SQL Server's
Management Console.

63
Modifying GParameters for Geography Types

• By default, GeoMedia is configured to use GEOMETRY data types.


• To configure your database for GEOGRAPHY, you would change the
following:
– Change the TypeForNativeGeometryStorage to geography
– Change the NativeGeometrySrid to one that matches your geographic
system. 4326 is WGS84.
– Use Database Utilities to set the DefaultCoordinateSystem to one that
matches the SRID you are using.

For best results, do not mix geometry types in the same database.

64
GeoMedia’s Scalar Metadata Functions

Four scalar functions are used to cast SQL Server's GEOMETRY/GEOGRAPHY


data type to/from the standard binary data type when reading/writing native
geometry records:
• Binary2SqlGeography – Converts the standard binary data type to the native
GEOGRAPHY data type when writing WKB geographic data.
• Binary2SqlGeometry – Converts the standard binary data type to the native
GEOMETRY data type when writing WKB geometry data.
• SqlGeography2Binary – Converts native GEOGRAPHY data type to the
standard binary data type when reading WKB data.
• SqlGeometry2Binary – Converts native GEOMETRY data type to the
standard binary data type when reading WKB data.

Note: Execute privileges are required on these four functions for any login
to a SQL Server database that does not have the db_owner role.
These functions only convert the data type used to store the data; they DO
NOT convert data between WKB and GDO formats.

65
Scalar Function Example

Here is an example of a select statement from GeoMedia:


SELECT [ID],dbo.SqlGeography2Binary([GRID_CELL]),[GRID_CELL_GDO]
FROM [dbo].[WorldGrid]

Here is an example of an Update:


UPDATE [dbo].[Interstates]
SET [LinearGeometry_SPA]=dbo.Binary2SqlGeometry(@P1),
[LinearGeometry]=@P2
WHERE [ID1]=@P3

And here is an Insert:


EXEC sp_executesql
N'INSERT INTO [dbo].[Cities]([Name], [PointGeometry_SPA], [PointGeometry])
VALUES (@P1,dbo.Binary2SqlGeometry(@P2),@P3)
SELECT SCOPE_IDENTITY()',N'@P1 ntext,@P2 image,@P3 image',N'CHUCK',
0x00000000010D7F00E00FEB0554C0BE8DD3D7F77D46400000000000000000,0xC8FFD20FB
C8CCF11ABDE08003601B7697F00E00FEB0554C0BE8DD3D7F77D46400000000000000000FFF
FFFFFFFFFEF3F00000000000000000000000000000000

66
Using GeoMedia Professional

• Once a connection is
established, the commands in
GeoMedia behave the same as
any other RW connection.
• Just remember to use the
correct data server here.
• Windows authentication is the
best choice for connecting to
SQL Server databases but both
methods are allowed.
• Behind the scenes, there are
some differences, particularly in
the following areas:
– Spatial Filtering
– Update Attributes

67
Existing Standard SQL Server Data

• Keep in mind that the 2 SQL Server data servers use different data models
and are not interchangeable.
– Workspaces that use SQL Server standard WILL NOT work with SQL Server
native.
– Similarly with libraries and the objects they contain.
– You cannot create libraries in SQL Server native warehouses either, the library will
need to be in a separate schema. This DOES NOT mean you cannot use libraries
with SQL Server Native, you CAN.
• If you have databases that currently utilize GeoMedia's standard SQL Server
data server, the best way to migrate them is to use one of the methods
discussed in the previous section.
• If you need more information on this, contact the instructor after the
workshop.

68
Creating Tables via GMP's Feature Class Definition

• The Feature Class Definition command in GeoMedia Professional can


add tables and columns and edit existing tables and columns as long as
the user account you are connected with has the correct permissions.
• The login must have the db_owner role assigned to create and edit tables.
• Remember, the geometry data type comes from GParameters so make
sure you set the coordinate system accordingly. This is why having a
default coordinate system is so important.
• Autonumber primary keys are automatically set to identity and clustered.

69
FCD Caveats

When editing tables using Feature Class Definition, the following caveats apply:
• Never change the primary key column of a table after the table has been created. This
could make the table inaccessible by GeoMedia Professional. If you need to do this, use
Database Utilities to drop the metadata before altering the table using SQL Server’s
own tools. You can re-add the metadata after making the table change.
• If the table has a spatial index, you will need to drop it before modifying the primary key.
• Do not change data types on existing columns using Feature Class Definition. If you
need to do this, drop the metadata first, make the data type change using SQL Server's
Management Studio, and then re-insert the metadata using Database Utilities.
• Renaming a table can take a long time if the table contains data, and by default, SQL
Server will disallow this operation. If you need this capability, you may need to activate
the capability using SQL Server's Management Studio.
• Copying an existing table will not work due to the way the metadata for the GDO to
native geometry relationship is handled. If you need to copy a table, use SQL Server's
Management Console.

Best Practice: Use SQL Server Console Manager to create and edit tables in a production
environment.

70
Default Geometry Naming Conventions

The SQL Server Spatial data server uses two storage columns:
• A native spatial column using either the GEOMETRY or GEOGRAPHY data type.
– GEOMETRY is the default native storage data type (SRID=0).
– GEOGRAPHY is fully supported but will require the use of a valid EPSG spatial reference
system identifier (SRID) .
• A binary column (varbinary(max)) storing the GDO (GeoMedia Data Object -
GeoMedia's native binary storage format) geometry blob used for unsupported
geometries like arcs, oriented points, text, and raster).
Every native spatial geometry column must have a corresponding GDO binary
column:
• If the table is created using Feature Class Definition, the following columns are
present in the base table for the feature class:

Note: For tables create outside of GeoMedia, specific extensions are not required as long
as the relationship between the native/GDO columns is specified in metadata.

71
Importing Spatial Data

The easiest way to get started using the SQL Server Spatial data server is by bulk importing
data from another data source. GeoMedia Professional has two commands that will move
data to SQL Server warehouses, Export to SQL Server and Output to Feature Classes.
• Export to SQL Server - creates a set of files and an import.bat script that will load a
SQL Server database from any data source that GeoMedia Professional is connected
to.
– The process will use the coordinate system of the GeoWorkspace for the output.
– The resulting export files use SQL Server’s CMDSQL and BCP to load the data.
– Imports can only be run on a SQL Server Administrative Client or on the system where SQL
Server is installed.
– This method is very fast and is ideal for bulk loading large amounts of data (>1000000 rows per
table).
• Output to Feature Classes - requires that metadata tables already exist in the target
SQL Server database.
– To manually create the metadata, use GeoMedia Professional’s Database Utilities, connect to
the new database using an account with the db_owner role, and then click Create Metadata
Tables.
– Once the metadata is created, you will be able to connect to the warehouse through GeoMedia
Professional and then use Output to Feature Classes to create feature classes.

Note: Both methods will create the required after insert and after update triggers for you.

72
Using Export to SQL Server

Three export options available:


• SQL Server 2012 Spatial (or later) – has support for
arcs.
• SQL Server 2008 Spatial – For 2008 R2, arcs are
stroked to linestrings.
• GeoMedia – Original GDO format.

Caveats:
• Export will use the workspace coordinate system.
• If the workspace CS is projected, the SRID will
automatically be selected (and set to 0).
• If the workspace CS is geographic, you will need to
select an SRID that matches it.
• By default, the data is exported to the \Warehouses
folder. You can change this location on the dialog
box.

Note: Make sure you select the correct SRID here. If


the SRID does not match the CS of the workspace,
your data will have serious issues.

Error conditions are not reported to the user, review


the log files.

73
Using Output to Feature Classes

• No real change to OTFC.


• It will use the settings in the GParameters metadata table to determine
whether to use a geometry or geography data type.
• It will also assign the SRID based on the value it finds in GParameters.
• If you are outputting to a new database, ensure that you have set these
parameters correctly.

74
Output to Feature Classes: Caveats

Target Coordinate System


• Maintain Source Coordinate System – Has the best performance, no
coordinate system transformation occurs. The data is written in the same
coordinate system as the input data.
• Specify New or select one from the list – If the target warehouse has a default
CS, then it will be chosen as the default output coordinate system. If no
default exists, a CS will be chosen for you from those currently available.

Performance
• OTFC is process intensive and when datasets get very large (over 250000
records), performance can suffer.
• Disabling Display target feature classes in map window can help performance.
• This process is not designed to be a bulk loader

- 75 -
Metadata Triggers

Maintenance Triggers (required for all spatial enabled tables)


• after insert – verifies that an insert only occurred on the native column or
both the native and GDO columns. An error will occur if the insert
operation is only applied to the GDO column.
• after update – if the update occurs only on the native column, a null is
written into the corresponding row of the GDO column. The GDO column
will be updated the next time GeoMedia edits the data. An error will occur
if the update operation is only applied to the GDO column.

Possible Data Loss!


• If an OrientedPointGeometry is stored in SQL Server, GeoMedia's binary
GDO geometry field contains the actual oriented point geometry, while the
native geometry field stores only the point location. When a non-
GeoMedia client updates the native POINT (x y z) geometry, the
orientation vector is lost.
• A more complicated scenario occurs when arcs are stored in the binary
GDO geometry and corresponding stroked polylines are stored in the
native geometry. In this case, information referencing the geometry as an
arc will be lost, and its stroked PolylineGeometry will remain.

Note: These triggers are part of the metadata required for the SQL
Server spatial data server to work correctly. Do not remove them!

76
Metadata Trigger Examples

AFTER INSERT example for table ROADS:


----
CREATE TRIGGER [dbo].[ROADS_GEOMETRY_INS] ON [dbo].[ROADS] AFTER INSERT AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT NULL FROM INSERTED
WHERE INSERTED.[CENTERLINE] IS NULL
AND INSERTED.[CENTERLINE_GDO] IS NOT NULL)
BEGIN
RAISERROR(N'Unsupported. Cannot specify value for GDO column only,
native column value must also be provided.',0, 1)
ROLLBACK TRANSACTION
END;
END;
----
GO

Note: If you create your own tables, these triggers will have to be created
manually.

77
Metadata Trigger Examples

AFTER UPDATE example for table ROADS:


CREATE TRIGGER [ROADS_GEOMETRY_UPG] ON [dbo].[ROADS] AFTER UPDATE AS
BEGIN
SET NOCOUNT ON;
IF UPDATE([CENTERLINE])
BEGIN
IF NOT UPDATE([CENTERLINE_GDO])
BEGIN
UPDATE [ROADS] SET [CENTERLINE_GDO] = NULL
WHERE EXISTS (SELECT NULL FROM INSERTED WHERE INSERTED.[ID] = [ROADS].[ID])
END;
END;
ELSE IF UPDATE([CENTERLINE_GDO])
BEGIN
RAISERROR('Unsupported. Cannot specify value for GDO column only,
native column value must also be provided.', 0, 1)
ROLLBACK TRANSACTION
END;
END;
----
GO

Note: If you create your own tables, these triggers will have to be created manually.

78
GDO to Native Spatial Type Matching

To write geometric data to SQL Server, GeoMedia’s Spatial data server converts
GeoMedia native GDO geometry format to SQL Server native spatial format using the
following:

Polygons are handled similarly. Raster geometries are treated like polygons.

79
Data type Matching

• Data type matching is the same


as the standard SQL Server data
server
• The table at right shows how the
SQL Server data types are
mapped to the GeoMedia types.
• Any SQL Server data types
missing from this list are
considered unsupported and are
ignored.

How can you utilize an unsupported


type?
Any ideas?

80
Default Spatial Indexes

Spatial filtering in GeoMedia will use standard SQL Server spatial filtering
operations. These rely on spatial indexes on the native geometry fields. For
tables created using GeoMedia Professional, the spatial indexes are created
automatically.
• For native geometries using the GEOGRAPHY data type, the spatial index is
created using the following syntax:
CREATE SPATIAL INDEX <TABLE_NAME>_<NATIVE_COLUMN_NAME>_sindx ON
<TABLE_NAME> (<NATIVE_COLUMN_NAME>);
• For native geometries using the GEOMETRY data type, the spatial index is
created using the following syntax:
CREATE SPATIAL INDEX <TABLE_NAME>_<NATIVE_COLUMN_NAME>_sindx ON
<TABLE_NAME> (<NATIVE_COLUMN_NAME>) WITH (BOUNDING_BOX =
(<XLowerBound>, <YLowerBound>, <XUpperBound>, <YUpperBound>))
• where <XLowerBound>, <YLowerBound>, <XUpperBound>, <YUpperBound>
are taken from the GParameters table.

Note: The indexes created by GeoMedia may not be optimal. The database
administrator should ensure that the spatial indexes are up to date and
optimal for the data stored. Or performance will be an issue.

81
Improving Spatial Index Performance

• GeoMedia will create default spatial index for you but they are not
optimal.
• Optimal spatial indexes depend on the bounding box and the
distribution of data within that box
• Unlike Oracle, data can lie outside the bounding box without causing a
performance degradation but the majority of data must be in the
bounding box.

Querying an optimal bounding box (SQL Server 2008)


WITH
ENVELOPE as (SELECT Geometry.STEnvelope() as ENVELOPE from State),
CORNERS as (SELECT ENVELOPE.STPointN(1) as POINT from ENVELOPE
UNION ALL SELECT ENVELOPE.STPointN(3) from ENVELOPE)
SELECT
ROUND(MIN(point.STX),0,1) as XLO,
ROUND(MIN(point.STY),0,1) as YLO,
ROUND(MAX(point.STX),0) as XHI,
ROUND(MAX(point.STY),0) as YHI
FROM CORNERS;

82
Improving Spatial Index Performance

The aggregation methods in SQL Server 2012 make the bounding box
calculations a lot easier

Querying an optimal bounding box (SQL Server 2012)

SELECT
ROUND(geometry::UnionAggregate(Geometry).STEnvelope().STPointN(1).STX,0,1) as XLO,
ROUND(geometry::UnionAggregate(Geometry).STEnvelope().STPointN(1).STY,0,1) as YLO,
ROUND(geometry::UnionAggregate(Geometry).STEnvelope().STPointN(3).STX,0) AS XHI,
ROUND(geometry::UnionAggregate(Geometry).STEnvelope().STPointN(3).STY,0) AS YHI
FROM State;

83
Using Existing Native Spatial Data

• If you have existing native spatial data, you will need to add a
varbinary(max) column to support the GeoMedia's binary GDO
geometry format .
• This column can be named anything, but it is best to make it similar to
the column name of the native geometry. This will make associating
the two columns a lot easier when metadata is assigned using
Database Utilities. For example, if the table ROADS contains a
geometry column called CENTERLINE, add a column called
CENTERLINE_GDO:

ALTER TABLE ROADS ADD COLUMN CENTERLINE_GDO VARBINARY(MAX)

• Once the binary column has been added, you will need to add the
metadata tables required by GeoMedia applications and then add the
metadata entries for each table you want to use as a feature class.
You can use Database Utilities for both of these operations.
• The final step will be to create the after insert and after update
triggers for each table.
84
Using Database Utilities – Creating Metadata Tables

• On connection, make sure you pick the


SQL Server Spatial data server! There are
2 now…
• Make a connection to your SQL Server
database using a login that has the
dbowner role on your database.
• Verify the connection information
• Then select Create Metadata Tables

Note: If this type of operation is handled by


your SQL Server DBA, then you can give
them the metadata.sql script generated by
Export to SQL Server (using the spatial
option) and they can run it manually.

85
Database Utilities – Inserting and Editing Metadata

Attribute Tab:
• If you are using identity based primary keys,
make sure you set the Autonumber Property.
Geometry Tab:
• Specify the geometry type depending on the
type of data stored in the table.
• Associate the native geometry field to the GDO
field.
• Assign the SRID that is used by the native
spatial data. For geometry data types, it will be
0. If you are using geographic data, you must
pick an SRID from the list and it MUST match
the coordinate system you assigned to the
feature class.
Other options:
• Once metadata is set, you can use the Edit
Metadata command to alter the settings or
Delete Metadata to delete existing metadata
entries.

86
Database Utilities – Coordinate System Operations

• Assigns GeoMedia coordinate system to


existing data.
• No Transformation will occur.
• Assign coordinate system can also be used
to assign a default CS to the current
database.
• You can also rename coordinate systems,
review coordinate system definitions, and
create new ones.

Best Practices
• Always set a default CS
• Always give your CS a meaningful name
• Always double verify you are using the
correct CS.

Note: This operation can be dangerous, make sure you


are assigning the correct CS for your data. Why?

87
Spatial Filtering

• Spatial filtering will use the spatial index created on


the tables' native geometry columns.
• The performance of spatial indexes can vary widely,
so if performance is an issue, consider re-creating
the spatial indexes using different parameters.
• GeoMedia applications have four different spatial
filter options:
– Coarse Overlap: uses SQL Server's Filter method to
return the results. This is generally the fastest performing
filter because it only compares the spatial index grid
cells; however, it will always pick up extraneous values.
– Overlap: uses SQL Server's two pass STIntersects
method. It may still pick up erroneous results but is
generally better than Coarse Overlap.
– Inside: This method uses SQL Server's two pass
STWithin method and gives the most accurate results. It
includes everything inside, up to, and including the
boundary of the filter area.
– Entirely Inside: uses SQL Server's two pass STWithin
method and the processes the final results on the client
(3 passes total). This is the slowest of the spatial filters.

88
Update Attributes

• GM applications will reference the GDO geometry column


for input geometries but on the database side, will use the
native storage as well. Both geometries are updated and
utilized depending on the task at hand.

89
Using UNDO/REDO

• If you use the Undo/Redo commands while editing the geometry or attributes
associated with tables that contain an identity column, be aware that the
numeric sequence is not preserved. Auto-increment identity columns are
usually assigned as primary key columns, and they should not be used as part
of a foreign key. Failure to heed this warning could invalidate view-join
definitions.
• For example, a row of your data consists of an identity field called ID that
contains the value 10, and there are 300 total records in this table such that
max(ID)=300. If you accidentally delete this row and use the Undo command
to get it back, ID will now be assigned the next available number in the auto-
increment sequence, in this case 301.
• The original ID=10 is not recoverable. In all cases, the next available
autonumber value will be obtained on an undo/redo operation; the previous
autonumber value will not be preserved. This is actually by design; it is how
Microsoft intends the auto-increment field to be used.

90
Editing Data Outside of GeoMedia

You can edit spatial data outside of GeoMedia using other applications including
directly thru SQL Server's console manager. Some things to remember:
• For spatial edits, only edit the native spatial data column, never edit the GDO
column.
• The maintenance trigger will clear the GDO column if edits are made to the
spatial column.
• The GDO column will be refreshed as needed from GeoMedia the next time
an edit is made from there.
• GeoMedia users will not be simultaneously aware of the external edits unless
an entry is written to the ModificationLog table.
• Modification Log Triggers can facilitate this and need to be manually created if
this workflow is a normal operation.

So, how does editing notification actually work in GeoMedia apps?

91
ModificationLog Triggers - Inserts

ModificationLog trigger example for Insert operations (using the Cities table):

CREATE TRIGGER [dbo].[CitiesGMTI] ON [dbo].[Cities] FOR INSERT AS SELECT


@@identity
DECLARE @TableID INT
if object_id('tempdb..#DisableModificationLog') is null
BEGIN
SELECT @TableID=id FROM SYSOBJECTS WHERE name='Cities'
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 1, convert(nvarchar(20),@TableID),
convert(nvarchar(255), inserted.[ID]) FROM inserted
END;
GO

92
ModificationLog Triggers - Updates

ModificationLog trigger example for Update operations:

CREATE TRIGGER [dbo].[CitiesGMTU] ON [dbo].[Cities] FOR UPDATE AS


DECLARE @TableID INT
if object_id('tempdb..#DisableModificationLog') is null
BEGIN
SELECT @TableID=id FROM SYSOBJECTS WHERE name='Cities'
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 2, convert(nvarchar(20),@TableID),
convert(nvarchar(255), deleted.[ID]) FROM deleted
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 2, convert(nvarchar(20),@TableID),
convert(nvarchar(255), inserted.[ID]) FROM inserted
END;
GO

Why do you need to handle both an insert and a delete?

93
ModificationLog Triggers - Deletes

ModificationLog trigger example for Delete operations:

CREATE TRIGGER [dbo].[CitiesGMTD] ON [dbo].[Cities] FOR DELETE AS


DECLARE @TableID INT
if object_id('tempdb..#DisableModificationLog') is null
BEGIN
SELECT @TableID=id FROM SYSOBJECTS WHERE name='Cities'
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 3, convert(nvarchar(20),@TableID),
convert(nvarchar(255), deleted.[ID]) FROM deleted
END;
GO

94
Using Views

• GeoMedia Professional makes no distinction between views and tables; it


treats a view just like any other feature class.
• The SQL Server Spatial data server handles read-write access to most types
of views as long as the views are key preserved. This means that the status of
the primary key in the base table is preserved in the view. One way to ensure
this is true is to include and preserve the primary key in the view definition.
• In a join-view, the primary key can come from either the left or the right side as
long as it retains its key status. It cannot come from both sides of the join and
still be updatable. In addition, only the side of the join containing the key will
be updatable. For full editing capability on a join view, an instead of trigger is
required.
• For a view to be treated as a spatial feature class, the view definition must
include both the native geometry column and GeoMedia's binary GDO
column. Metadata is also required to see the view in GeoMedia applications,
and Database Utilities can be used to insert the required metadata.
• For views to be updatable in GeoMedia Professional, there must also be an
entry for the key column in the GindexColumns metadata table. This is
required for both spatial and non-spatial feature classes that are view based.

95
Handling Modification logging with Views
To make logging work with views, you need to add an entry to the base table trigger that handles the
modification to the view. For example, if you have a simple view on States called STATES_VIEW, you
could use the following trigger to handle notification for inserts:

CREATE TRIGGER [dbo].[StatesGMTI] ON [dbo].[States] FOR INSERT AS


DECLARE @TableID INT
IF object_id('tempdb..#DisableModificationLog') is null
BEGIN
SELECT @TableID=id FROM SYSOBJECTS WHERE name='States';
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 1, convert(nvarchar(20),@TableID), convert(nvarchar(255), inserted.[ID])
FROM inserted;
SELECT @TableID=id FROM SYSOBJECTS WHERE name='States_View';
INSERT INTO ModificationLog([Type], [ModifiedTableID], KeyValue1)
SELECT 1, convert(nvarchar(20),@TableID), convert(nvarchar(255), inserted.[ID])
FROM inserted;
END;
GO

The trigger in the above example will handle edit notification for both the table and the view, but
GeoMedia will still attempt to write another notification for the view itself. To stop this second notification
event, another trigger needs to be created on the view using the view name:

CREATE TRIGGER dbo.States_ViewGMTI ON dbo.States FOR INSERT AS


DECLARE @TableID INT
if object_id('tempdb..#DisableModificationLog') is null
BEGIN
SELECT @TableID=1
END
GO

96
Useful Stored Procedures and Functions
GMPSpatialUtilities.sql – This is a collection of procedures to simplify standard maintenance operations in SQL
Server spatial. It is open source and available on the web but it is not Intergraph sanctioned.

EXEC GMPVersion
============================================================
** INTERGRAPH **
** GeoMedia Native SQL Server Spatial Utilities - GMP **
============================================================
** Author: Chuck Woodbury, Senior Technical Consultant **
** Intergraph Technology Services **
============================================================
Version............................................ 06.01.11
Date............................................. 06/01/2012
Bug Reports and Support...................... Via Email Only
Email......................... [email protected]
============================================================

Setting Defaults
These default parameters to use for creating new tables via GMP. These procedures write results to
GParameters:

• EXECUTE GMPSetDefaultGeography - Set the default data type to geography


• EXECUTE GMPSetDefaultGeometry - Set the default data type to geometry
• EXECUTE GMPSetDefaultMBR @Xlo, @Ylo, @Xhi, @Yhi - Set the data range for geometry
• EXECUTE GMPSetDefaultSRID @SRID - set the default SRID for geography

97
Useful Stored Procedures and Functions

INDEXING: Creating and dropping SQL Server default spatial indexes


• EXECUTE GMPCreateSpatialIndexes
-- Creates spatial indexes for all spatial data type in database
• EXECUTE GMPCreateSpatialIndexOn @TableName
-- Creates a spatial index on the spatial data types in the specified
table
• EXECUTE GMPDropSpatialIndexes
-- Drops all spatial indexes in the database
• EXECUTE GMPDropSpatialIndexOn @TableName
-- Drops spatial indexes on the specified table
• EXECUTE GMPSetSRIDAll @SRID
-- Sets the SRID for all spatial columns in the database
• EXECUTE GMPSetSRIDOn @TableName, @SRID
-- Sets the SRID on the spatial data types in the specified table

98
Useful Stored Procedures and Functions

METADATA: GDO Metadata procedures

• EXECUTE GMPCountMetadataFor @TableName


-- Count the GDO metadata entries for a table
• EXECUTE GMPDeleteMetadataFor @TableName
-- Delete metadata for the specified table
• EXECUTE GMPListMetadataFor @TableName
-- List metadata entries for the specified table
• EXECUTE GMPLogDataModificationFor @TableName, @KeyValue, @ModType
-- Log data modification – best used in a trigger
• EXECUTE GMPCreateModLogTriggerOn @TableName
-- Create modificationlog triggers
• EXECUTE GMPSetMetadataFor @TableName
-- Set the default metadata for the specified table

99
Useful Stored Procedures

UTILITIES: Misc stored Procedures


• EXECUTE GMPChangeOwner2DBO
-- The table ownership to DBO
• EXECUTE GMPCreateGDOTriggersOn @TableName
-- Create the required GDO triggers for a table
• EXECUTE GMPDeleteProcedure @ProcName
-- Procedure deleter
• EXECUTE GMPDeleteTable @TableName
-- Table deleter
• EXECUTE GMPNullZeroLength
-- Nulls zero length text strings
• EXECUTE GMPVersion
-- Collection version and support information
• EXECUTE GMPHelpme
-- List of procedures and syntax

GRIDS: Grid Creation procedures


• EXECUTE GMPCreateGeometryGrid @TableName, @xlo, @ylo, @xhi, @yhi,
@DivX, @DivY, @SRID
-- Create a grid feature class based on geometry
• EXECUTE GMPCreateGeographyGrid @TableName, @LonLo, @LatLo, @LonHi, @LatHi,
@DivLong, @DivLat, @SRID
-- Create a grid feature class based on geography

100
Lesson 3: Using GeoMedia

• Goals
– Create a GeoMedia database
– Examine metadata tables
– Setting GeoMedia defaults
– Using Feature Class Definition
– Basic Editing and Maintenance Triggers
– Export/Import operations
– Output to Feature Class
– Optimizing Indexes
• If you finish early, take a look at lesson 4 and 5.
Questions? Comments?

Thank You for Attending! I hope you have enjoyed this workshop.

Dankie dat jy, ‫الشكر‬, Благодаря, 三江源, Hvala, Děkuji, Tak, Dank je, Kiitos, Merci, Grazas,
Gracias, Danke, De takke, Σας ευχαριστώ, ‫תודה‬, धन्यवाद, Köszönöm, Þakka þér,
Grazie, ありがとうございます, 감사합니다, Dziękuję, Obrigado, Mulţumesc, Спасибо,
Хвала, Ďakujem, Tack, ขอบคุณ, teşekkürler, Спасибі, Cảm ơn, Diolch yn fawr, Dzięk ci,
Bedankt, Eyxaristo, Faleminderit, Shukran, Tatenda, Efcharisto, Asante, Paldies, Tika
Hoki, Ngeyabonga, Thenks, Dhanyavaadaalu, Mersi, Ngiyabonga!

Chuck Woodbury

Senior Consultant, Technology Services


Hexagon Geospatial

102
Optional Information

Oracle Locator versus SQL Server spatial

Feature Oracle SQL Server 2008


Format Object based numbers and Binary. Uses .NET Common
arrays. Language Runtime data types.
Storage SQL/MM SQL/MM
Dimensions 2, 2.5, 3 and 4 D. 2.5 D
Ref System EPSG (and others) EPSG
Standard OGC, SFS, and SQL/MM OGC and SFS 1.1
Indexing RTree Grid based BTree
Standard Open but proprietary OGC with extensions

103
Analysis Comparison

104
Analysis Comparison

105
Analysis Comparison

106
Analysis Comparison

107
Oracle Locator versus SQL Server spatial

• All editions of Oracle and SQL Server come with basic spatial storage and
analysis capability built in.
• Both have a good set of spatial analysis capabilities
• Both have a robust spatial indexing capability.
• Oracle has the edge in some key areas:
– Advanced spatial capabilities in Oracle Spatial add-on, SQL Server has no
equivalent.
– Includes coordinate transform methods and support for custom SRID’s, not
available in SQL Server.
– Handles a much larger set of data both overall and per row.
• SQL Server has edge in
– Easier to program against with CLR extensions.
– Easier to load and query spatial data.
– Built in viewer for spatial query results.
– Less Complex and easier to manage
– Less expensive

108

You might also like