SlideShare a Scribd company logo
1 of 26
SPATIAL SUPPORT IN
SQL SERVER 2008 R2
Ing. Eduardo Castro Martinez
ecastro@simsasys.com
http://tiny.cc/comwindows
http://ecastrom.blogspot.com
Presentation Source
• SQL Server 2008 R2 Update for Developers Training Kit
  • http://www.microsoft.com/download/en/details.aspx?id=16281


• Building Location-Aware Applications with the SQL Server
 Spatial Library
  • Ed Katibah, Torsten Grabs and Olivier Meyer SQL Server Microsoft
   Corporation
Relational and Non-Relational Data
• Relational data uses simple data types
  • Each type has a single value
  • Generic operations work well with the types
• Relational storage/query may not be optimal for
  • Hierarchical data
  • Sparse, variable, property bags
• Some types
  • benefit by using a custom library
  • use extended type system (complex types, inheritance)
  • use custom storage and non-SQL APIs
  • use non-relational queries and indexing
Spatial Data
• Spatial data provides answers to location-based queries
  • Which roads intersect the Microsoft campus?

  • Does my land claim overlap yours?
  • List all of the Italian restaurants within 5 kilometers

• Spatial data is part of almost every database
  • If your database includes an address
Spatial Data Types
• The Open Geospatial Consortium defines a hierarchy of
 spatial data types
 • Point

 • Linestring
 • Polygon
 • MultiPoint
 • MultiLinestring
 • MultiPolygon
 • GeomCollection

 • Non-instanciable classes based on these
OGC Hierarchy of Spatial Types
SQL Server 2008 Spatial Summary
OVERVIEW                                            FEATURES
• 2 Spatial Data Types (CLR UDT)                    • 2D Vector Data Support
• Comprehensive set of Spatial Methods              • Open Geospatial Consortium Simple
• High Performance Spatial Indexes                    Features for SQL compatible
• Spatial Library                                   • Supported By Major GIS Vendors
• Sink/Builder APIs                                   ESRI, Intergraph, Autodesk, Pitney Bowes, Safe, etc.
• Management Studio Integration                     • Standard feature in SQL Server
                                                      Express, Workgroup, Web, Standard, Enterprise and
                                                      Developer
                                                    • Support for very large spatial objects


DETAILS
• Geography data type for geodetic Data
• Geometry data type for planar Data
• Standard spatial methods
   STIntersects, STBuffer, STLength, STArea, etc.
• Standard spatial format support
   WKT, WKB and GML
• Multiple spatial indexes per column
• Create new CLR-based spatial methods
  with the Builder API
• Redistributable Spatial Library
   SQLSysClrTypes
SQL Server Spatial Library Resources
SQL SERVER SPATIAL LIBRARY
Microsoft SQL Server System CLR Types
The SQL Server System CLR Types package contains the components
implementing the geometry, geography, and hierarchy id types in SQL Server
2008 R2. This component can be installed separately from the server to allow
client applications to use these types outside of the server.
X86 Package(SQLSysClrTypes_x86.msi) – 3,342 KB
X64 Package (SQLSysClrTypes._x64msi) – 3,459 KB
IA64 Package(SQLSysClrTypes_ia64.msi) – 5,352 KB

Search for: Microsoft SQL Server 2008 Feature Pack, October 2008
---
CODEPLEX SQL Server Spatial Tools
Code Samples Utilizing the SQL Server Spatial Library
SQL Server Spatial Tools – including source code for tools

Search for: Codeplex SQL Server Spatial Tools
SQL Server 2008 and Spatial Data
• SQL Server supports two spatial data types
  • GEOMETRY - flat earth model
  • GEOGRAPHY - round earth model
• Both types support all of the instanciable OGC types
  • InstanceOf method can distinguish between them
• Supports two dimension data
  • X and Y or Lat and Long members
  • Z member - elevation (user-defined semantics)
  • M member - measure (user-defined semantics)
GEOGRAPHY Requirements
• GEOGRAPHY type has additional requirements

• Coordinate order is
  • Longitude/Latitude for WKT, WKB
  • Latitude/Longitude for GML

• Exterior polygon rings must have their describing
 coordinates in counter-clockwise order (left-hand rule)
 with interior rings (holes) in clockwise-order (right-hand
 rule)
• A single GEOGRAPHY object cannot span more than a
 logical hemisphere
SPATIAL DATA
demo
Properties and Methods
• The spatial data types are exposed as SQLCLR UDTs
  • Use '.' syntax for properties
  • Use '.' syntax for instance methods
  • Use '::' syntax for static methods
  • Methods and Properties are case-sensitive
• Each type uses a set of properties and methods that
 correspond to OGC functionality
  • With Extensions
  • Geometry implements all OGC properties and methods
    • Geography implements most OGC properties and methods
  • 2-D vector only implemented
Input
• Spatial data is stored in a proprietary binary format
• Instance of the type can be NULL
• Can be input as
  • Well Known binary - ST[Type]FromWKB
  • Well Known text - ST[Type]FromText
  • Geography Markup Language (GML) - GeomFromGml
• Can also use SQLCLR functions
  • Parse
  • Point - extension function
• Input from SQLCLR Type - SqlGeometry, SqlGeography
• Spatial builder API –
 Populate, IGeometrySink/IGeographySink
Output
• Spatial Data Can Be Output As
  • Well Known binary - STAsBinary
  • Well Known text - STAsText
  • GML - AsGml
  • Text with Z and M values - AsTextZM
• SQLCLR standard method
  • ToString - returns Well Known text
• As SQLCLR object - SqlGeometry, SqlGeography
• Other useful formats are GeoRSS, KML
  • Not Directly Supported
SRID
• Each instance of a spatial type must have an SRID
  • Spatial Reference Identifier
• SRID specifies the specification used to compute it
  • SRID 4326 - GPS, default for GEOGRAPHY
  • SRID 4269 - usually used by ESRI
  • SRID 0 - no special reference, default for GEOMETRY
• Methods that use multiple spatial types (e.g., STDistance)
 must have types with matching SRID
  • Else method returns NULL
• Geography instance must reference one of these SRID
 stored in sys.spatial_reference_systems
Useful Methods/Properties
• Descriptive
  • STArea
  • STLength
  • STCentroid
• Relation between two instances
  • STIntersects
  • STDistance
• Manipulation
  • STUnion
  • STSymDifference
• Collections
  • STGeometryN
  • STPointN
Sample Query




      SELECT *
 Which roads intersect Microsoft’s main
      FROM roads                             campus?
      WHERE roads.geom.STIntersects(@ms)=1
Extension Methods
• SQL Server 2008 extends OGC methods
 • MakeValid - Converts to OGC valid instance

 • BufferWithTolerence - similar to STBuffer, allows approximation and
  variation
 • Reduce - Simplify a complex geography or geometry
 • NumRings, RingN - polygons with multiple rings
 • GML support
 • Z and M properties and AsTextZM method
 • Filter - provides a quick intersection set but with false positives

 • EnvelopeCenter,EnvelopeAngle for Geography types
Spatial Indexes
• SQL Server Spatial Indexes Based on B-Trees
  • Uses tessellation to tile 2D to linear
  • Divides space into grid of cells(uses Hilbert algorithm)
• Meant as a first level of row elimination
  • Can produce false positives
  • Never false negatives
• You specify
   • Bounding box of top level grid - GEOMETRY index only
   • Cells per object - number of cells recorded for matching
   • Grids
     • Four Grid Levels
     • Three Grid Densities Per Level - Low, Medium, High
Tessellation process
SPATIAL ANALYTICS
demo
What is CEP?
Complex Event Processing (CEP) is the continuous and
incremental processing of event streams from multiple
sources based on declarative query and pattern specifications
with near-zero latency.
              Database Applications Event-driven Applications
Query         Ad-hoc queries or        Continuous standing
Paradigm      requests                 queries
Latency       Seconds, hours, days     Milliseconds or less
Data Rate     Hundreds of events/sec   Tens of thousands of
                                       events/sec or more
                                          Event
                           request
                                                       output
                                        input          stream
               response                stream
Shuttle Tracker




    519,000+ data points, covering 1 day of operation
Review
• Spatial data provides answers to location-based queries

• SQL Server supports two spatial data types
  • GEOMETRY - flat earth model
  • GEOGRAPHY - round earth model

• Spatial data has
  • Useful properties and functions
  • Library of spatial functions
  • Three standard input and output formats
  • Spatial indexes
Resources
• SQL Server Spatial Data Technology Center
 http://www.microsoft.com/sql/2008/technologies/spatial.mspx
• Whitepaper: Delivering Location Intelligence with Spatial Data
 http://www.microsoft.com/sql/techinfo/whitepapers/spatialdata.mspx
• MSDN Webcast: Building Spatial Applications with SQL Server
  2008, Event ID: 1032353123
• Whitepaper: What's New for XML in SQL Server 2008
 http://www.microsoft.com/sql/techinfo/whitepapers/sql_2008_xml.mspx
• Whitepaper: Managing Unstructured Data with SQL Server
 2008
 http://www.microsoft.com/sql/techinfo/whitepapers/sql_2008_unstructure
 d.mspx
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market
     conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.
                                 MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related Content

What's hot

Image enhancement
Image enhancementImage enhancement
Image enhancement
Ayaelshiwi
 
Introdution to Landsat and Google Earth Engine
Introdution to Landsat and Google Earth EngineIntrodution to Landsat and Google Earth Engine
Introdution to Landsat and Google Earth Engine
Veerachai Tanpipat
 

What's hot (20)

Image filtering in Digital image processing
Image filtering in Digital image processingImage filtering in Digital image processing
Image filtering in Digital image processing
 
Spatial Database Systems
Spatial Database SystemsSpatial Database Systems
Spatial Database Systems
 
Datamining - On What Kind of Data
Datamining - On What Kind of DataDatamining - On What Kind of Data
Datamining - On What Kind of Data
 
Conceptual database design
Conceptual database designConceptual database design
Conceptual database design
 
Image enhancement
Image enhancementImage enhancement
Image enhancement
 
Developing Efficient Web-based GIS Applications
Developing Efficient Web-based GIS ApplicationsDeveloping Efficient Web-based GIS Applications
Developing Efficient Web-based GIS Applications
 
active and passive sensors
active and passive sensorsactive and passive sensors
active and passive sensors
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Data Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsData Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlations
 
Spatial Databases
Spatial DatabasesSpatial Databases
Spatial Databases
 
Introdution to Landsat and Google Earth Engine
Introdution to Landsat and Google Earth EngineIntrodution to Landsat and Google Earth Engine
Introdution to Landsat and Google Earth Engine
 
Evolution of Esri Data Formats Seminar
Evolution of Esri Data Formats SeminarEvolution of Esri Data Formats Seminar
Evolution of Esri Data Formats Seminar
 
PostgreSQL - Case Study
PostgreSQL - Case StudyPostgreSQL - Case Study
PostgreSQL - Case Study
 
Lecture 1b introduction to arc gis
Lecture 1b  introduction to arc gisLecture 1b  introduction to arc gis
Lecture 1b introduction to arc gis
 
Vector data model
Vector data model Vector data model
Vector data model
 
SPATIAL FILTERING IN IMAGE PROCESSING
SPATIAL FILTERING IN IMAGE PROCESSINGSPATIAL FILTERING IN IMAGE PROCESSING
SPATIAL FILTERING IN IMAGE PROCESSING
 
Presentations on web database
Presentations on web databasePresentations on web database
Presentations on web database
 
Conversion of Existing Data
Conversion of Existing DataConversion of Existing Data
Conversion of Existing Data
 
RapidMiner: Data Mining And Rapid Miner
RapidMiner: Data Mining And Rapid MinerRapidMiner: Data Mining And Rapid Miner
RapidMiner: Data Mining And Rapid Miner
 
Fundamental Steps of Digital Image Processing & Image Components
Fundamental Steps of Digital Image Processing & Image ComponentsFundamental Steps of Digital Image Processing & Image Components
Fundamental Steps of Digital Image Processing & Image Components
 

Viewers also liked

Descubriendo los datos espaciales en sql server 2012
Descubriendo los datos espaciales en sql server 2012Descubriendo los datos espaciales en sql server 2012
Descubriendo los datos espaciales en sql server 2012
John Bulla
 
X query language reference
X query language referenceX query language reference
X query language reference
Steve Xu
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
Conor Mc Elhinney
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
drywallbmb
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
Ehtisham Ali
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programming
Steve Xu
 
Css introduction
Css introductionCss introduction
Css introduction
Sridhar P
 
5 tsssisu sql_server_2012
5 tsssisu sql_server_20125 tsssisu sql_server_2012
5 tsssisu sql_server_2012
Steve Xu
 

Viewers also liked (20)

Descubriendo los datos espaciales en SQL Server
Descubriendo los datos espaciales en SQL ServerDescubriendo los datos espaciales en SQL Server
Descubriendo los datos espaciales en SQL Server
 
Descubriendo los datos espaciales en sql server 2012
Descubriendo los datos espaciales en sql server 2012Descubriendo los datos espaciales en sql server 2012
Descubriendo los datos espaciales en sql server 2012
 
Module02
Module02Module02
Module02
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)
 
X query language reference
X query language referenceX query language reference
X query language reference
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
 
Module07
Module07Module07
Module07
 
Sql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAUSql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAU
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programming
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
 
Alasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAlasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScript
 
Css introduction
Css introductionCss introduction
Css introduction
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
 
Module01
Module01Module01
Module01
 
5 tsssisu sql_server_2012
5 tsssisu sql_server_20125 tsssisu sql_server_2012
5 tsssisu sql_server_2012
 
Module08
Module08Module08
Module08
 
Module04
Module04Module04
Module04
 
Module06
Module06Module06
Module06
 

Similar to Spatial Data in SQL Server

Similar to Spatial Data in SQL Server (20)

Spatial Data in SQL Server
Spatial Data in SQL ServerSpatial Data in SQL Server
Spatial Data in SQL Server
 
Suburface 2021 IBM Cloud Data Lake
Suburface 2021 IBM Cloud Data LakeSuburface 2021 IBM Cloud Data Lake
Suburface 2021 IBM Cloud Data Lake
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
Spatial
SpatialSpatial
Spatial
 
[Research] azure ml anatomy of a machine learning service - Sharat Chikkerur
[Research] azure ml  anatomy of a machine learning service - Sharat Chikkerur[Research] azure ml  anatomy of a machine learning service - Sharat Chikkerur
[Research] azure ml anatomy of a machine learning service - Sharat Chikkerur
 
Serverless SQL
Serverless SQLServerless SQL
Serverless SQL
 
Azure Stream Analytics
Azure Stream AnalyticsAzure Stream Analytics
Azure Stream Analytics
 
Using Apache Calcite for Enabling SQL and JDBC Access to Apache Geode and Oth...
Using Apache Calcite for Enabling SQL and JDBC Access to Apache Geode and Oth...Using Apache Calcite for Enabling SQL and JDBC Access to Apache Geode and Oth...
Using Apache Calcite for Enabling SQL and JDBC Access to Apache Geode and Oth...
 
Apache Geode Meetup, Cork, Ireland at CIT
Apache Geode Meetup, Cork, Ireland at CITApache Geode Meetup, Cork, Ireland at CIT
Apache Geode Meetup, Cork, Ireland at CIT
 
CosmosDB.pptx
CosmosDB.pptxCosmosDB.pptx
CosmosDB.pptx
 
Azure CosmosDb - Where we are
Azure CosmosDb - Where we areAzure CosmosDb - Where we are
Azure CosmosDb - Where we are
 
Sql Server2008
Sql Server2008Sql Server2008
Sql Server2008
 
Ssn0020 ssis 2012 for beginners
Ssn0020   ssis 2012 for beginnersSsn0020   ssis 2012 for beginners
Ssn0020 ssis 2012 for beginners
 
ElasticSearch as (only) datastore
ElasticSearch as (only) datastoreElasticSearch as (only) datastore
ElasticSearch as (only) datastore
 
Introduction to Apache Geode (Cork, Ireland)
Introduction to Apache Geode (Cork, Ireland)Introduction to Apache Geode (Cork, Ireland)
Introduction to Apache Geode (Cork, Ireland)
 
Enterprise geodatabase sql access and administration
Enterprise geodatabase sql access and administrationEnterprise geodatabase sql access and administration
Enterprise geodatabase sql access and administration
 
Azure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud DatabaseAzure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud Database
 
ADL/U-SQL Introduction (SQLBits 2016)
ADL/U-SQL Introduction (SQLBits 2016)ADL/U-SQL Introduction (SQLBits 2016)
ADL/U-SQL Introduction (SQLBits 2016)
 
Closer Look at Cloud Centric Architectures
Closer Look at Cloud Centric ArchitecturesCloser Look at Cloud Centric Architectures
Closer Look at Cloud Centric Architectures
 
Apache Geode Meetup, London
Apache Geode Meetup, LondonApache Geode Meetup, London
Apache Geode Meetup, London
 

More from Eduardo Castro

More from Eduardo Castro (20)

Introducción a polybase en SQL Server
Introducción a polybase en SQL ServerIntroducción a polybase en SQL Server
Introducción a polybase en SQL Server
 
Creando tu primer ambiente de AI en Azure ML y SQL Server
Creando tu primer ambiente de AI en Azure ML y SQL ServerCreando tu primer ambiente de AI en Azure ML y SQL Server
Creando tu primer ambiente de AI en Azure ML y SQL Server
 
Seguridad en SQL Azure
Seguridad en SQL AzureSeguridad en SQL Azure
Seguridad en SQL Azure
 
Azure Synapse Analytics MLflow
Azure Synapse Analytics MLflowAzure Synapse Analytics MLflow
Azure Synapse Analytics MLflow
 
SQL Server 2019 con Windows Server 2022
SQL Server 2019 con Windows Server 2022SQL Server 2019 con Windows Server 2022
SQL Server 2019 con Windows Server 2022
 
Novedades en SQL Server 2022
Novedades en SQL Server 2022Novedades en SQL Server 2022
Novedades en SQL Server 2022
 
Introduccion a SQL Server 2022
Introduccion a SQL Server 2022Introduccion a SQL Server 2022
Introduccion a SQL Server 2022
 
Machine Learning con Azure Managed Instance
Machine Learning con Azure Managed InstanceMachine Learning con Azure Managed Instance
Machine Learning con Azure Managed Instance
 
Novedades en sql server 2022
Novedades en sql server 2022Novedades en sql server 2022
Novedades en sql server 2022
 
Sql server 2019 con windows server 2022
Sql server 2019 con windows server 2022Sql server 2019 con windows server 2022
Sql server 2019 con windows server 2022
 
Introduccion a databricks
Introduccion a databricksIntroduccion a databricks
Introduccion a databricks
 
Pronosticos con sql server
Pronosticos con sql serverPronosticos con sql server
Pronosticos con sql server
 
Data warehouse con azure synapse analytics
Data warehouse con azure synapse analyticsData warehouse con azure synapse analytics
Data warehouse con azure synapse analytics
 
Que hay de nuevo en el Azure Data Lake Storage Gen2
Que hay de nuevo en el Azure Data Lake Storage Gen2Que hay de nuevo en el Azure Data Lake Storage Gen2
Que hay de nuevo en el Azure Data Lake Storage Gen2
 
Introduccion a Azure Synapse Analytics
Introduccion a Azure Synapse AnalyticsIntroduccion a Azure Synapse Analytics
Introduccion a Azure Synapse Analytics
 
Seguridad de SQL Database en Azure
Seguridad de SQL Database en AzureSeguridad de SQL Database en Azure
Seguridad de SQL Database en Azure
 
Python dentro de SQL Server
Python dentro de SQL ServerPython dentro de SQL Server
Python dentro de SQL Server
 
Servicios Cognitivos de de Microsoft
Servicios Cognitivos de de Microsoft Servicios Cognitivos de de Microsoft
Servicios Cognitivos de de Microsoft
 
Script de paso a paso de configuración de Secure Enclaves
Script de paso a paso de configuración de Secure EnclavesScript de paso a paso de configuración de Secure Enclaves
Script de paso a paso de configuración de Secure Enclaves
 
Introducción a conceptos de SQL Server Secure Enclaves
Introducción a conceptos de SQL Server Secure EnclavesIntroducción a conceptos de SQL Server Secure Enclaves
Introducción a conceptos de SQL Server Secure Enclaves
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Spatial Data in SQL Server

  • 1. SPATIAL SUPPORT IN SQL SERVER 2008 R2 Ing. Eduardo Castro Martinez ecastro@simsasys.com http://tiny.cc/comwindows http://ecastrom.blogspot.com
  • 2. Presentation Source • SQL Server 2008 R2 Update for Developers Training Kit • http://www.microsoft.com/download/en/details.aspx?id=16281 • Building Location-Aware Applications with the SQL Server Spatial Library • Ed Katibah, Torsten Grabs and Olivier Meyer SQL Server Microsoft Corporation
  • 3. Relational and Non-Relational Data • Relational data uses simple data types • Each type has a single value • Generic operations work well with the types • Relational storage/query may not be optimal for • Hierarchical data • Sparse, variable, property bags • Some types • benefit by using a custom library • use extended type system (complex types, inheritance) • use custom storage and non-SQL APIs • use non-relational queries and indexing
  • 4. Spatial Data • Spatial data provides answers to location-based queries • Which roads intersect the Microsoft campus? • Does my land claim overlap yours? • List all of the Italian restaurants within 5 kilometers • Spatial data is part of almost every database • If your database includes an address
  • 5. Spatial Data Types • The Open Geospatial Consortium defines a hierarchy of spatial data types • Point • Linestring • Polygon • MultiPoint • MultiLinestring • MultiPolygon • GeomCollection • Non-instanciable classes based on these
  • 6. OGC Hierarchy of Spatial Types
  • 7. SQL Server 2008 Spatial Summary OVERVIEW FEATURES • 2 Spatial Data Types (CLR UDT) • 2D Vector Data Support • Comprehensive set of Spatial Methods • Open Geospatial Consortium Simple • High Performance Spatial Indexes Features for SQL compatible • Spatial Library • Supported By Major GIS Vendors • Sink/Builder APIs ESRI, Intergraph, Autodesk, Pitney Bowes, Safe, etc. • Management Studio Integration • Standard feature in SQL Server Express, Workgroup, Web, Standard, Enterprise and Developer • Support for very large spatial objects DETAILS • Geography data type for geodetic Data • Geometry data type for planar Data • Standard spatial methods STIntersects, STBuffer, STLength, STArea, etc. • Standard spatial format support WKT, WKB and GML • Multiple spatial indexes per column • Create new CLR-based spatial methods with the Builder API • Redistributable Spatial Library SQLSysClrTypes
  • 8. SQL Server Spatial Library Resources SQL SERVER SPATIAL LIBRARY Microsoft SQL Server System CLR Types The SQL Server System CLR Types package contains the components implementing the geometry, geography, and hierarchy id types in SQL Server 2008 R2. This component can be installed separately from the server to allow client applications to use these types outside of the server. X86 Package(SQLSysClrTypes_x86.msi) – 3,342 KB X64 Package (SQLSysClrTypes._x64msi) – 3,459 KB IA64 Package(SQLSysClrTypes_ia64.msi) – 5,352 KB Search for: Microsoft SQL Server 2008 Feature Pack, October 2008 --- CODEPLEX SQL Server Spatial Tools Code Samples Utilizing the SQL Server Spatial Library SQL Server Spatial Tools – including source code for tools Search for: Codeplex SQL Server Spatial Tools
  • 9. SQL Server 2008 and Spatial Data • SQL Server supports two spatial data types • GEOMETRY - flat earth model • GEOGRAPHY - round earth model • Both types support all of the instanciable OGC types • InstanceOf method can distinguish between them • Supports two dimension data • X and Y or Lat and Long members • Z member - elevation (user-defined semantics) • M member - measure (user-defined semantics)
  • 10. GEOGRAPHY Requirements • GEOGRAPHY type has additional requirements • Coordinate order is • Longitude/Latitude for WKT, WKB • Latitude/Longitude for GML • Exterior polygon rings must have their describing coordinates in counter-clockwise order (left-hand rule) with interior rings (holes) in clockwise-order (right-hand rule) • A single GEOGRAPHY object cannot span more than a logical hemisphere
  • 12. Properties and Methods • The spatial data types are exposed as SQLCLR UDTs • Use '.' syntax for properties • Use '.' syntax for instance methods • Use '::' syntax for static methods • Methods and Properties are case-sensitive • Each type uses a set of properties and methods that correspond to OGC functionality • With Extensions • Geometry implements all OGC properties and methods • Geography implements most OGC properties and methods • 2-D vector only implemented
  • 13. Input • Spatial data is stored in a proprietary binary format • Instance of the type can be NULL • Can be input as • Well Known binary - ST[Type]FromWKB • Well Known text - ST[Type]FromText • Geography Markup Language (GML) - GeomFromGml • Can also use SQLCLR functions • Parse • Point - extension function • Input from SQLCLR Type - SqlGeometry, SqlGeography • Spatial builder API – Populate, IGeometrySink/IGeographySink
  • 14. Output • Spatial Data Can Be Output As • Well Known binary - STAsBinary • Well Known text - STAsText • GML - AsGml • Text with Z and M values - AsTextZM • SQLCLR standard method • ToString - returns Well Known text • As SQLCLR object - SqlGeometry, SqlGeography • Other useful formats are GeoRSS, KML • Not Directly Supported
  • 15. SRID • Each instance of a spatial type must have an SRID • Spatial Reference Identifier • SRID specifies the specification used to compute it • SRID 4326 - GPS, default for GEOGRAPHY • SRID 4269 - usually used by ESRI • SRID 0 - no special reference, default for GEOMETRY • Methods that use multiple spatial types (e.g., STDistance) must have types with matching SRID • Else method returns NULL • Geography instance must reference one of these SRID stored in sys.spatial_reference_systems
  • 16. Useful Methods/Properties • Descriptive • STArea • STLength • STCentroid • Relation between two instances • STIntersects • STDistance • Manipulation • STUnion • STSymDifference • Collections • STGeometryN • STPointN
  • 17. Sample Query SELECT * Which roads intersect Microsoft’s main FROM roads campus? WHERE roads.geom.STIntersects(@ms)=1
  • 18. Extension Methods • SQL Server 2008 extends OGC methods • MakeValid - Converts to OGC valid instance • BufferWithTolerence - similar to STBuffer, allows approximation and variation • Reduce - Simplify a complex geography or geometry • NumRings, RingN - polygons with multiple rings • GML support • Z and M properties and AsTextZM method • Filter - provides a quick intersection set but with false positives • EnvelopeCenter,EnvelopeAngle for Geography types
  • 19. Spatial Indexes • SQL Server Spatial Indexes Based on B-Trees • Uses tessellation to tile 2D to linear • Divides space into grid of cells(uses Hilbert algorithm) • Meant as a first level of row elimination • Can produce false positives • Never false negatives • You specify • Bounding box of top level grid - GEOMETRY index only • Cells per object - number of cells recorded for matching • Grids • Four Grid Levels • Three Grid Densities Per Level - Low, Medium, High
  • 22. What is CEP? Complex Event Processing (CEP) is the continuous and incremental processing of event streams from multiple sources based on declarative query and pattern specifications with near-zero latency. Database Applications Event-driven Applications Query Ad-hoc queries or Continuous standing Paradigm requests queries Latency Seconds, hours, days Milliseconds or less Data Rate Hundreds of events/sec Tens of thousands of events/sec or more Event request output input stream response stream
  • 23. Shuttle Tracker 519,000+ data points, covering 1 day of operation
  • 24. Review • Spatial data provides answers to location-based queries • SQL Server supports two spatial data types • GEOMETRY - flat earth model • GEOGRAPHY - round earth model • Spatial data has • Useful properties and functions • Library of spatial functions • Three standard input and output formats • Spatial indexes
  • 25. Resources • SQL Server Spatial Data Technology Center http://www.microsoft.com/sql/2008/technologies/spatial.mspx • Whitepaper: Delivering Location Intelligence with Spatial Data http://www.microsoft.com/sql/techinfo/whitepapers/spatialdata.mspx • MSDN Webcast: Building Spatial Applications with SQL Server 2008, Event ID: 1032353123 • Whitepaper: What's New for XML in SQL Server 2008 http://www.microsoft.com/sql/techinfo/whitepapers/sql_2008_xml.mspx • Whitepaper: Managing Unstructured Data with SQL Server 2008 http://www.microsoft.com/sql/techinfo/whitepapers/sql_2008_unstructure d.mspx
  • 26. © 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  1. Simple types only store one value, and work with generic methods like adding, subtracting, assignment. Relational storage isn’t optimal for storing and querying hierarchies, location based data, or coping with sparse data where the data required per row differs.Some data types benefit from having complex logic for parsing and processing, and the benefit from other programming features such as inheritance. What's more the storage requirements and indexing requirements require special processing as the storage is not byte ordered.
  2. Reference: http://www.sqlskills.com/BLOGS/BOBB/post/Spatial-Data-a-niche-or-a-tool-for-the-masses.aspxSpatial data allows you to answer questions in 2 dimensions, often related to location based information. Almost every database contains location information, i.e.. Addresses, however they don’t know where those addresses are. They don’t know that 4th street is next to 3rd street and that 1st avenue intersects both of them.
  3. The spatial implementation in SQL Server 2008 is based on the OGC standards.There is a hierarchy of Spatial data instances starting with a point then a line and finally a polygon. This relates to their dimensionality, a point has 0 dimensions, a line has 1 and a polygon has 2. You also have MULTI instances which contain more than one of the other types and then the collection type which can contain any of the other types
  4. This is the hierarchy.Not the terms curve and surface, this implies 3 dimensions which SQL Server spatial data doesn’t support, it only supports 2 dimensions. More on that later.
  5. Unlike other providers SQL splits planar and non planar data into two separate types. Geometry and geography.Non planar data is all about projections. If you think about maps of the world they have to use some form of projection to convert the elliptical surface of the earth into a flat map. In other providers they store the data in a planar projection and then perform the projection to workout the geographic calculations.We mentioned earlier that the spatial data is only in 2 dimensions. Whilst you can hold two other values Z and M for points they are not used in any of the spatial methods.
  6. The geometry type covers a planar surface which is infinite your x and y can go on for ever. With the Geography type that's not the case. Latitude goes from -90 degrees to 90degrees. Longitude goes from 0 to 360.The order of how these will be parsed in the WKB (Well-Known Binary) and WKT (Well-Known Text) formats will be switched before RTM to fit in with the other products on the market.A geography shape must be contained with a single hemisphere. This doesn’t have to the north or south hemisphere but half of the earth essentially the maximum angle mad at the centre by lines to the edges cannot be greater than 180.Because the earth is a finite shape, you have to define your points in a certain order to ensure that you include the area within your shape and not the area outside of the shape. If you find you shapes are violating the hemisphere rule you might have your points going in the wrong order.
  7. This demo will show how to use the SQL Server spatial data types with data from the Mondial database, which contains latitude and longitude fields for three of the tables: City, Mountain, and Island. We will use this information to construct a new column of type Geography, and then use the spatial methods of the Geography data type to perform SQL spatial queries on this data.The material for this demo can be found at the Source folder of the Spatial demo. Make sure to read the demo document to get started with this demo.
  8. Reference: http://www.sqlskills.com/blogs/bobb/2007/06/24/SQLServerSystemDataTypesImplementedInNET.aspx Some new SQL Server 2008 data types are implemented/exposed as .NET UDTs. These include the spatial data types Geometry and Geography, and also HierarchyID, mentioned later in this slideset.The Date/Time series of data type ARE NOT implemented as UDT, and therefore are referred to as "new T-SQL data types".Spatial data types are implemented as CLR User defined types. YOU DO NOT HAVE TO ENABLE CLR ON THE SERVER TO USE SPATIAL DATA TYPES.You get some benefits because of this. You can call methods on the types directly. You can also call static methods on the base type by using ::. It is the later that can be used to create instances of the types.Note: You are calling methods on the types directly and so the methods and properties are case sensitive.The OGC spec defines a set of methods that should be supported, the Geometry type supports all of them. The Geography type doesn’t. It will support more by RTM but not all of them.
  9. Spatial data is created from a defined format, that is either a text base format, a binary format or an XML format.WKT is the text representationWKB is the binary formGML is the XML structure.Only WKT support passing in Z and M values.WKT is more readable but as its text it doesn’t perform as well as the binary format. It is stored in the database in a proprietary binary format. If you have that format you can also create an instance from that, if you are passing data from a client application using this format is the best to use. You create an instance by assigning a string to a type, using parse, or one of the STFROM... Methods.Much of the data in the industry is in shape file format. This is a format define by ESRI and for which you will need an application to convert to a format usable by SQL ServerFor more information on the spatial builder API and an example, see http://blogs.msdn.com/isaac/archive/2008/05/30/our-upcoming-builder-api.aspx
  10. You can output any of the formats that are used to create an instance.Other formats used by applications such as Google maps an virtual earth are not supported directly. You have to create these yourself more on that later.
  11. SRID defines the unitof measure datum (shape of the ellipsoid) and projection. Each piece of geography data requires a spatial reference.You cannot combine data of different SRIDs, as this is like comparing apples and pears.You need to make sure you use the correct reference to ensure you calculations are correct. Lengths and areas will differ under different spatial references when dealing with geography data.There is no mechanism for translating between spatial references in SQL Server. You will need a 3rd party application to achieve that.
  12. One of the killer features of spatial types is the methods they bring. You have methods that provide information about shapes.Methods that show the relationship between shapesMethods used to combine and manipulate shapes. If you’ve done set theory and venn diagrams these methods will make sense.Finally methods that provide information about the structure of the shape. Because of the limitations of SQLCLR these are not collections put rather methods that take an index to return the relevant value.
  13. SQL Server extends the spatial types beyond what is in the spec. The following are the methods and there are more coming. EnveloperCentre and EnvelopeAngle provide the information used to determine the bounds of the geography type and whether it fits in a hemisphere.
  14. Index is an internal table. One row represents a hierarchy of intersections of cells with in the gridEach cell that a shape intersects is recorded in the index.4 levels of grid used to provide greater accuracy. Each cell in grid is split into x more cells in the next level grid.Number of cells in each grid is defined when you create the index.
  15. Top three show the level 1, Level 2 and then Level 3 and 4 intersections.If we stored all of these intersections we would have 85 matches. What we do find is that some of the cells are complete matches these don’t need to be broken down to the lower level cells. Like in Figure 4.However we still have a large number of matches, depending on the cells per object setting on the index the tessellation process will stop once it hits the limit as we have in Figure 5.This shows how imprecise the index is. It is only meant as a filter to avoid doing a very expensive calculation on all the data.
  16. This demo is aimed to show the spatial capabilities of SQL Server 2008 integrated with ASP.NET. The demo relies on SQL Server to store and perform calculations on the new Geography data types; and on Virtual Earth to consume the spatial data and render it on a map.The material for this demo can be found at the Source folder of the Spatial demo. Make sure to read the demo document to get started with this demo.