Western Mass Hosting's .Net Articles

Home / .Net

Cookie Notice

This site utilizes cookies to improve your browsing experience, analyze the type of traffic we receive, and serve up proper content for you. If you wish to continue browsing, you must agree to allow us to set these cookies. If not, please visit another website.

Geographic Location Lookup System for SQL Server and MySQL

Introduction to Geographic Data Management

When working with location-based data across different database platforms, understanding how to efficiently store and query geographic information is essential. This guide provides comprehensive implementations for both Microsoft SQL Server and MySQL, focusing on a flexible geographic area lookup system rather than just store locations. The solutions presented here can be adapted for various use cases including service area identification, regional analysis, or population distribution studies.

Database Schema Implementation

Microsoft SQL Server Geographic Table Structure

SQL Server’s robust geography data type provides excellent support for spatial operations. This implementation uses a computed column to automatically generate geographic points from latitude/longitude coordinates:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

CREATE TABLE [Geography].[LocationPoints](
    [LocationID] [bigint] IDENTITY(1,1) NOT NULL,
    [LocationCode] [varchar](20) NULL,
    [Latitude] [float] NULL,
    [Longitude] [float] NULL,
    [LocationName] [varchar](255) NULL,
    [Region] [varchar](100) NULL,
    [AdminDivision] [varchar](255) NULL,
    [LocationType] [varchar](100) NULL,
    [GeoPoint] AS ([geography]::Point([Latitude],[Longitude],(4326))) PERSISTED,
 CONSTRAINT [PK_LocationPoints] PRIMARY KEY CLUSTERED 
(
    [LocationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
      ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

MySQL Spatial Data Table Structure

MySQL’s spatial extensions provide similar functionality with a slightly different syntax:

CREATE TABLE `LocationPoints` (
    `LocationID` bigint NOT NULL AUTO_INCREMENT,
    `LocationCode` varchar(20) DEFAULT NULL,
    `Latitude` double DEFAULT NULL,
    `Longitude` double DEFAULT NULL,
    `LocationName` varchar(255) DEFAULT NULL,
    `Region` varchar(100) DEFAULT NULL,
    `AdminDivision` varchar(255) DEFAULT NULL,
    `LocationType` varchar(100) DEFAULT NULL,
    `GeoPoint` POINT NOT NULL SRID 4326,
    PRIMARY KEY (`LocationID`),
    SPATIAL INDEX(`GeoPoint`),
    INDEX (`LocationCode`),
    INDEX (`Region`),
    INDEX (`LocationType`)
) ENGINE=InnoDB;

Geographic View Implementations

SQL Server Optimized View

CREATE VIEW [Geography].[LocationView] WITH SCHEMABINDING
AS
SELECT 
    LocationID, 
    LocationCode, 
    Latitude, 
    Longitude, 
    LocationName, 
    Region, 
    AdminDivision, 
    LocationType, 
    GeoPoint
FROM Geography.LocationPoints
GO

MySQL Geographic View

CREATE VIEW `LocationView` AS
SELECT 
    LocationID, 
    LocationCode, 
    Latitude, 
    Longitude, 
    LocationName, 
    Region, 
    AdminDivision, 
    LocationType, 
    GeoPoint
FROM LocationPoints;

Radius Search Procedures

SQL Server Geographic Search Procedure

This procedure finds all locations within a specified radius of a given point:

CREATE PROCEDURE [Geography].[FindLocationsInRadius]
    @ReferenceCode VARCHAR(20),
    @RadiusKm FLOAT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lat FLOAT;
    DECLARE @lon FLOAT;
    DECLARE @referencePoint GEOGRAPHY;

    SELECT @lat = Latitude, @lon = Longitude 
    FROM Geography.LocationPoints 
    WHERE LocationCode = @ReferenceCode;

    SET @referencePoint = geography::Point(@lat, @lon, 4326);

    SELECT 
        LocationID, 
        LocationCode, 
        LocationName, 
        Region, 
        AdminDivision,
        (@referencePoint.STDistance([GeoPoint]) / 1000) AS DistanceKm
    FROM Geography.LocationPoints
    WHERE @referencePoint.STDistance([GeoPoint]) <= (@RadiusKm * 1000)
    ORDER BY DistanceKm;
END
GO

MySQL Radius Search Procedure

DELIMITER //
CREATE PROCEDURE `FindLocationsInRadius`(
    IN p_ReferenceCode VARCHAR(20),
    IN p_RadiusKm FLOAT
)
BEGIN
    DECLARE v_lat DOUBLE;
    DECLARE v_lon DOUBLE;
    DECLARE v_point POINT;

    SELECT Latitude, Longitude INTO v_lat, v_lon 
    FROM LocationPoints WHERE LocationCode = p_ReferenceCode LIMIT 1;

    SET v_point = ST_SRID(POINT(v_lon, v_lat), 4326);

    SELECT 
        LocationID, 
        LocationCode, 
        LocationName, 
        Region, 
        AdminDivision,
        (ST_Distance_Sphere(v_point, GeoPoint) / 1000) AS DistanceKm
    FROM LocationPoints
    WHERE ST_Distance_Sphere(v_point, GeoPoint) <= (p_RadiusKm * 1000)
    ORDER BY DistanceKm;
END //
DELIMITER ;

Advanced Geographic Queries

Finding Locations Within a Boundary (SQL Server)

CREATE PROCEDURE [Geography].[FindLocationsWithinArea]
    @Boundary GEOGRAPHY
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        LocationID, 
        LocationCode, 
        LocationName, 
        Region,
        AdminDivision
    FROM Geography.LocationPoints
    WHERE @Boundary.STContains(GeoPoint) = 1
    ORDER BY LocationName;
END
GO

MySQL Polygon Area Search

DELIMITER //
CREATE PROCEDURE `FindLocationsWithinPolygon`(
    IN p_PolygonWKT TEXT
)
BEGIN
    DECLARE v_polygon POLYGON;

    SET v_polygon = ST_GeomFromText(p_PolygonWKT, 4326);

    SELECT 
        LocationID, 
        LocationCode, 
        LocationName, 
        Region,
        AdminDivision
    FROM LocationPoints
    WHERE ST_Within(GeoPoint, v_polygon) = 1
    ORDER BY LocationName;
END //
DELIMITER ;

Implementation Considerations

When implementing a geographic lookup system, several important factors should be considered:

Data accuracy is paramount - ensure your coordinate data comes from reliable sources and is properly validated. The spatial reference system (SRID 4326 in these examples) should be consistently applied throughout your application to prevent calculation errors.

Performance optimization requires proper indexing strategies. Both SQL Server and MySQL benefit from spatial indexes on the geographic columns, but remember that spatial indexes behave differently than traditional indexes. Regular monitoring and query optimization are essential as your dataset grows.

For applications requiring high precision over large distances, consider more advanced geographic libraries or extensions that account for geodetic calculations. While the built-in functions provided by SQL Server and MySQL work well for most use cases, specialized scenarios might require additional mathematical considerations.

The system's flexibility allows adaptation to various geographic lookup needs. By modifying the stored procedures or adding additional parameters, you can implement features like:

  • Multi-point route analysis
  • Density heatmaps
  • Regional clustering
  • Proximity alerts

Remember that geographic calculations are computationally intensive. Implement appropriate caching strategies and consider pre-calculating frequently needed results where possible. For web applications, implementing these calculations at the database level rather than in application code generally provides better performance.

Like This Article? Share It!

Our Privacy Policy

Last Updated: June 18th, 2025

Introduction

Western Mass Hosting (“we,” “our,” or “us”) respects the privacy of all individuals and organizations that interact with our services. This Privacy Policy establishes our practices regarding the collection, use, disclosure, and protection of personal information for visitors to our website and clients utilizing our managed hosting and WordPress services. By accessing our website or engaging our services, you acknowledge that you have read and understood this policy in its entirety.

Scope and Applicability

This Privacy Policy governs our handling of information collected through our corporate website and in the course of providing managed hosting, WordPress maintenance, and development services. In accordance with global privacy regulations, we serve as a Data Controller for information related to our business operations and client relationships. When processing data on behalf of our clients through hosted services, we act as a Data Processor under applicable data protection laws.

Information We Collect

We collect various categories of information necessary to provide and improve our services. This includes personal contact and payment details provided during account registration, technical information such as IP addresses and device characteristics for security purposes, and records of communications through support channels. For clients utilizing our hosting services, we may process end-user data stored within client websites, though we do not control or monitor the collection practices of such data.

Purpose and Legal Basis for Processing

We process personal information only when we have proper justification under applicable laws. The primary legal bases for our processing activities include the necessity to fulfill contractual obligations to our clients, our legitimate business interests in maintaining and improving our services, and in limited cases, explicit consent for specific marketing communications. We maintain detailed records of processing activities to demonstrate compliance with legal requirements.

Use of Collected Information

The information we collect serves multiple business purposes. Primarily, we use this data to deliver and maintain reliable hosting services, including server provisioning, performance monitoring, and technical support. We also utilize information for business operations such as billing, customer relationship management, and service improvement initiatives. Security represents another critical use case, where we analyze data to detect and prevent fraudulent activity or unauthorized access to our systems.

Data Sharing and Third-Party Disclosures

We engage with carefully selected third-party service providers to support our operations, including cloud infrastructure providers, payment processors, and customer support platforms. These relationships are governed by strict contractual agreements that mandate appropriate data protection measures. We may disclose information when legally required to comply with court orders, government requests, or to protect our legal rights and the security of our services.

International Data Transfers

As a global service provider, we may transfer and process data in various locations worldwide. When transferring personal data originating from the European Economic Area or other regulated jurisdictions, we implement appropriate safeguards such as Standard Contractual Clauses and rely on adequacy decisions where applicable. Our subprocessors, including AWS Lightsail, maintain robust compliance certifications to ensure the protection of transferred data.

Data Retention Practices

We retain personal information only for as long as necessary to fulfill the purposes outlined in this policy. Client account information is typically maintained for five years following service termination to comply with legal and financial reporting obligations. Backup data associated with hosting services is automatically purged after thirty days, as specified in our Terms of Service. For data processed on behalf of clients, retention periods are determined by the respective client’s policies and instructions.

Security Measures

We implement comprehensive technical and organizational security measures to protect personal information against unauthorized access, alteration, or destruction. Our security program includes network encryption protocols, regular vulnerability assessments, strict access controls, and employee training on data protection best practices. We maintain incident response procedures to address potential security breaches and will notify affected parties where required by law.

Individual Rights

Individuals whose personal data we process may exercise certain rights under applicable privacy laws. These rights may include requesting access to their information, seeking correction of inaccurate data, requesting deletion under specific circumstances, and objecting to particular processing activities. We have established procedures to handle such requests in accordance with legal requirements, typically responding within thirty days of receipt. Requests should be submitted to our designated Data Protection Officer through the contact information provided in this policy.

Cookies and Tracking Technologies

Our website employs various technologies to enhance user experience and analyze site performance. Essential cookies are used for basic functionality and security purposes, while analytics cookies help us understand how visitors interact with our site. Marketing cookies are only deployed with explicit user consent. Visitors can manage cookie preferences through their browser settings or our cookie consent tool.

Policy Updates and Notifications

We periodically review and update this Privacy Policy to reflect changes in our practices or legal obligations. Material changes will be communicated to affected clients through email notifications at least thirty days prior to implementation. Continued use of our services following such notifications constitutes acceptance of the revised policy.

Contact Information

For questions or concerns regarding this Privacy Policy or our privacy practices, please contact our Data Protection Officer at [email protected] or by mail at:

Western Mass Hosting
22 Orlando. St.,
Feeding Hills, MA 01030.

We take all privacy-related inquiries seriously and will respond promptly to legitimate requests. For clients with specific data processing agreements, please reference your contract for any additional terms that may apply to our handling of your data.

Like This Article? Share It!