Does anyone know how to get the bounding box for a recordset with a query in SQL Server Spatial? I have tried STEnvelope but it returns the bounding box for each individual record in the recordset. I want a single bounding box for the entire recordset. I know that I can create a feature layer and use GetBoundingBox, but I really want to get the answer directly from SQL Server.
Spatial Query for Bounding Box
Charles,
I couldn’t find a good way to get that bounding box, here we created a store procedure to implement it, please have a try. (Please remember to replace GeometryColumnName and TableName)
--------------------------------------------------------------
DECLARE @polygon01 geometry;
DECLARE @polygon02 geometry;
DECLARE mycursor cursor for select GeometryColumnName from TableName;
open mycursor;
fetch mycursor into @polygon01;
fetch mycursor into @polygon02;
set @polygon01 = @polygon01.STUnion(@polygon02.STEnvelope()).STEnvelope();
fetch mycursor into @polygon02;
while @@FETCH_STATUS = 0
begin
if (@polygon02 Is not NULL)
begin
set @polygon01 = @polygon01.STUnion(@polygon02.STEnvelope()).STEnvelope();
end
fetch mycursor into @polygon02;
end;
SELECT @polygon01.STAsBinary();
CLOSE myCursor;
DEALLOCATE myCursor;
--------------------------------------------------------------------------------------
Thanks,
Ben
Ben,
Thanks for the reply. I hadn't found any information searching the web, but I thought it was pretty basic and I must have missed it somehow.
Charles
Charles,
My guess as to why they left this out is that since databases are designed to be inserted and modified in real-time that the bounding box is only valid for a point in time. Also calculating it take quite a few resources. If they wanted to keep a cached quick lookup value they would need to visit every record on any update or delete. On an insert they can safety make it bigger but on update or delete then the whole ball of way needs to be recalculated. I am not even sure if they keep all of the bounding boxes for each record. Using an R-tree or other spatial indexes the original bounding box can be lost.
If they didn’t keep a changed value then every time you called it they have to visit every record which is very expensive. If you expose easy to use methods that take up a bunch of resources then people tend to abuse them as they do not know how much overhead it requires. Interestingly the stored proc really hits home what is going on, we need to visit every row. Anyway just a guess.
I will also talk with Ben about this proc. It seems that we are using a Union to put the bounding boxes together for each record. I am not sure the overhead of the Union but it will surely be faster just to cache in the MaxX, MaxY, MinX and MinY as we loop and construct the bounding box at the end. This way we avoid the Union all together.
David