Friday, February 24, 2012

complex insert statement

I have this stored procedure that returns a rowid, distance. It has a latitude, longitude, and range as inputs, it takes the latitude and longitude and computes a distance with every lat/long in a table PL_CustomerGeocode. Once that distance is computed it compares that distance with the range, and then returns the rowid, distance if the distance is <= range. I have the SELECT statement down, but now i just need to enter this information into a seperate table PL_Distance with (rowid, distance) as columns. The sql statement is as follows, and i cant figure out where the rowid part is an the distance part is:

DECLARE @.DegreesToRadians float

SET @.DegreesToRadians = Pi()/180

SELECT rowid, Cast(distance As numeric(9,3)) AS distance
FROM (SELECT rowid, CASE WHEN @.srcLat = geocodeLat And @.srcLong = geocodeLong THEN 0.0
WHEN ABS(Arc) > 1 THEN 0.0
ELSE 3963.1 * 2 * asin(Power(Arc, 0.5)) END AS distance
FROM (SELECT Power(sin(DLat/2),2) + cos(@.srcLat*@.DegreesToRadians)*cos(geocodeLat*@.DegreesToRadians)*Power(sin(DLong/2),2) AS Arc, rowid,geocodeLat,geocodeLong
FROM (SELECT @.srcLong*@.DegreesToRadians-geocodeLong*@.DegreesToRadians AS DLong,
@.srcLat*@.DegreesToRadians-geocodeLat*@.DegreesToRadians AS DLat,
rowid,
geocodeLat,
geocodeLong
FROM dbo.PL_CustomerGeoCode) AS x) AS y) AS z
WHERE distance <= @.range

Can't you just insert the rows returned by your query?

DECLARE @.DegreesToRadians float
SET @.DegreesToRadians = Pi()/180
INSERT INTO PL_Distance (rowid, distance)
SELECT rowid, Cast(distance As numeric(9,3)) AS distance
FROM (SELECT rowid, CASE WHEN @.srcLat = geocodeLat And @.srcLong = geocodeLong THEN 0.0
WHEN ABS(Arc) > 1 THEN 0.0
ELSE 3963.1 * 2 * asin(Power(Arc, 0.5)) END AS distance
FROM (SELECT Power(sin(DLat/2),2) + cos(@.srcLat*@.DegreesToRadians)*cos(geocodeLat*@.DegreesToRadians)*Power(sin(DLong/2),2) AS Arc, rowid,geocodeLat,geocodeLong
FROM (SELECT @.srcLong*@.DegreesToRadians-geocodeLong*@.DegreesToRadians AS DLong,
@.srcLat*@.DegreesToRadians-geocodeLat*@.DegreesToRadians AS DLat,
rowid,
geocodeLat,
geocodeLong
FROM dbo.PL_CustomerGeoCode) AS x) AS y) AS z
WHERE distance <= @.range

No comments:

Post a Comment