Home Forums SQL Server 2005 T-SQL (SS2K5) request on a query to capture the cell area a given x,y coordinate would be found in? RE: request on a query to capture the cell area a given x,y coordinate would be found in?

  • Hi,

    If you are only dealing with squares it is quite easy.

    Firstly you only need the top left and bottom right co-ordinates:

    CREATE TABLE Squares

    (CellNo CHAR(2) NOT NULL,

    TopLeftX INT NOT NULL,

    TopLeftY INT NOT NULL,

    BottomRightX INT NOT NULL,

    BottomRightY INT NOT NULL);

    INSERT INTO Squares VALUES

    ('A1', 0, 0, 100, 100),

    ('A2', 0, 101, 100, 200),

    ('B1', 101, 0, 200, 100),

    ('B2', 101, 101, 200, 200);

    Secondly, to make it scale to 10,000+ records you need to index the four co-ordinates. I would cluster the table on these columns:

    ALTER TABLE Squares

    ADD CONSTRAINT SquaresCoordinates UNIQUE CLUSTERED (TopLeftX, TopLeftY, BottomRightX, BottomRightY);

    Lastly, you just need to query for any values where the X and the Y each falls between the upper left and bottom right range. You can use a join as Dwain showed you above or you can specify the points in a where clause.

    SELECT

    *

    FROM

    Squares

    WHERE

    (25 BETWEEN TopLeftX AND BottomRightX

    AND 130 BETWEEN TopLeftY AND BottomRightY)

    OR

    (105 BETWEEN TopLeftX AND BottomRightX

    AND 40 BETWEEN TopLeftY AND BottomRightY);

    The SQL Guy @ blogspot[/url]

    @SeanPearceSQL

    About Me[/url]