views:

36

answers:

1

Hello All...

I have a following scenario in my SQL Server 2005 database.

zipcodes table has following fields and value (just a sample):

zipcode     latitude   longitude
-------     --------   ---------
65201      123.456     456.789
65203      126.546     444.444

and place table has following fields and value :

id     name     zip      latitude   longitude
--     ----     ---      --------   ---------
1      abc      65201     NULL        NULL
2      def      65202     NULL        NULL
3      ghi      65203     NULL        NULL
4      jkl      65204     NULL        NULL

Now, my requirement is like I want to compare my zip codes of place table and update the available latitude and longitude fields from zipcode table.

And there are some of the zipcodes which has no entry in zipcode table, so that should remain null.

And the major issue is like I have more then 50,00,000 records in my db. So, query should support this feature.

I have tried some of the solutions but unfortunately not getting proper output.

Any help would be appreciated...

+5  A: 

You can try something like

UPDATE place
SET     latitude = z.latitude,
        longitude = z.longitude
FROM    place p INNER JOIN
        zipcodes z ON p.zip = z.zipcode

See example

DECLARE @zipcodes TABLE(
        zipcode VARCHAR(10),
        latitude   FLOAT,
        longitude FLOAT
)

DECLARe @place TABLE(
        id INT,
        name VARCHAR(10),
        zip VARCHAR(10),
        latitude FLOAT,
        longitude FLOAT
)

INSERT INTO @zipcodes SELECT '65201',123.456,456.789 
INSERT INTO @zipcodes SELECT '65203',126.546,444.444

INSERT INTO @place SELECT 1,'abc','65201',NULL,NULL 
INSERT INTO @place SELECT 2,'def','65202',NULL,NULL 
INSERT INTO @place SELECT 3,'ghi','65203',NULL,NULL 
INSERT INTO @place SELECT 4,'jkl','65204',NULL,NULL 

UPDATE @place
SET     latitude = z.latitude,
        longitude = z.longitude
FROM    @place p INNER JOIN
        @zipcodes z ON p.zip = z.zipcode

SELECT  *
FROM @place

You can verify this from documentation

UPDATE (Transact-SQL)

astander
Hey, Thanks @astander... It works for me....
Nirmal