Search code examples
sql-server-2008geometrygeospatialgeography

SQL 2008 geography & geometry - which to use?


I'm creating a Google map mashup and am using SQL 2008.

I will have a large number of points on the earth and will want to perform various calculations on them in SQL - such as selecting all points contained within a particular polygone, or select all points within 10km of XY.

I have never used and SQL spatial features before. Should I use the geography or the geometry datatype for this?


Solution

  • Geography is the type that is intended for plotting points on the earth.

    If you have a table that stores Google Maps points like this:

    CREATE TABLE geo_locations (
        location_id       uniqueidentifier  NOT NULL,
        position_point    geography         NOT NULL
    );
    

    then you could fill points in it with this stored procedure:

    CREATE PROCEDURE proc_AddPoint
        @latitude     decimal(9,6),
        @longitude    decimal(9,6),
        @altitude     smallInt
    AS
    
    DECLARE @point     geography = NULL;
    
    BEGIN
    
        SET NOCOUNT ON;
    
        SET @point = geography::STPointFromText('POINT(' + CONVERT(varchar(15), @longitude) + ' ' + 
                                                           CONVERT(varchar(15), @latitude) + ' ' + 
                                                           CONVERT(varchar(10), @altitude) + ')', 4326)
    
        INSERT INTO geo_locations
        (
            location_id, 
            position_point
        )
        VALUES 
        (
            NEWID(),
            @point
        );
    
    END
    

    Then if you want to query for the latitude, longitude and altitude, simply use the following query format:

    SELECT
        geo_locations.position_point.Lat  AS latitude,
        geo_locations.position_point.Long AS longitude,
        geo_locations.position_point.Z    AS altitude
    FROM
        geo_locations;