Working with SQL Server Spatial - Workshop
Working with SQL Server Spatial - Workshop
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
• 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
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
Note: Added in SQL Server 2012 and expanded to full globe in 2014.
11
Geometry and Geography Differences
• 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)
13
More on SRIDs…
14
Storage Tolerance
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:
16
So how much data can actually be stored?
• 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)
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.
• 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)
000000000140000000000000004010000000000000,
where:
– 1-byte integer 00 or 0: big endian
– 4-byte integer 00000001 or 1 POINT (2D)
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
23
DDL Operations
Or
Existing:
ALTER TABLE MyGeometryTable
ADD SpatialDataCol GEOMETRY);
Or
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
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)
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
or for 3D
28
DML Operations – Other insert examples
29
DML Operations – Updates using WKT
Updates work like any other column updates, just use the type and
method for your specific data:
30
Table Constraints
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
SELECT GeometryCol.STAsText()
FROM MyGeometryTable
SELECT GeometryCol.ToString()
FROM MyGeometryTable;
SELECT GeometryCol.AsTextZM()
FROM MyGeometryTable;
33
Query Operation Examples
Here are a some examples for a table called Cities with a PointGeometry
column:
34
Displaying Results Graphically
35
Geometry Validation
.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
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:
but to get a point in between, you need to know the number of points that make
up the entire line:
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:
Specific to polygon, you may need to return just the exterior ring or find
and return a specific interior ring:
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.
.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.
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.
45
Spatial Indexing Restrictions
46
Spatial Indexing Syntax
Simple Syntax
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:
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
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
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:
51
Analysis Functions
• .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)
53
Analysis Functions (GEOMETRY ONLY)
54
Other geometry based functions
55
Additional Methods for Arcs in SQL Server 2012
56
Aggregate Methods in SQL Server 2012
57
Creating Spatial Views
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
• 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).
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
62
Metadata Requirements - GeoMedia
63
Modifying GParameters for Geography Types
For best results, do not mix geometry types in the same database.
64
GeoMedia’s Scalar Metadata Functions
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
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
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
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.
73
Using Output to Feature Classes
74
Output to Feature Classes: Caveats
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
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
Note: If you create your own tables, these triggers will have to be created
manually.
77
Metadata Trigger Examples
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
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.
82
Improving Spatial Index Performance
The aggregation methods in SQL Server 2012 make the bounding box
calculations a lot easier
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:
• 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
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
Best Practices
• Always set a default CS
• Always give your CS a meaningful name
• Always double verify you are using the
correct CS.
87
Spatial Filtering
88
Update Attributes
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.
91
ModificationLog Triggers - Inserts
ModificationLog trigger example for Insert operations (using the Cities table):
92
ModificationLog Triggers - Updates
93
ModificationLog Triggers - Deletes
94
Using Views
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:
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:
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:
97
Useful Stored Procedures and Functions
98
Useful Stored Procedures and Functions
99
Useful Stored Procedures
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
102
Optional Information
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