views:

58

answers:

2

Hello there,

i have a Problem with a query.

I have a huge Table with Zipcodes from Germany called 'Postleitzahlen'. There is another table with Companies called 'Firmen'

Structure is like this:

Firmen
------
ID
City
State
ZipCode


Postleitzahlen
--------------
ZipCode
State

Now I want, all empty ( '' or NULL ) State-fields of Firmen updated with their correspendants of Postleitzahlen

That's my actual query:

UPDATE 
    Firmen
SET 
    Firmen.State = Postleitzahlen.State 
FROM
    Postleitzahlen
INNER JOIN 
    Firmen ON Postleitzahlen.ZipCode = Firmen.ZipCode 
WHERE 
    (
      Firmen.State = ''
   OR Firmen.State IS NULL )

I get a response with xx affected rows, but in fact, there's nothing updated.

Can someone help me?

Thanks in advance.

  • dennis
+2  A: 

That looks like it should work correctly. What I would do is run the below query:

SELECT Firmen.State,Postleitzahlen.State 
FROM
    Postleitzahlen
INNER JOIN 
    Firmen ON Postleitzahlen.ZipCode = Firmen.ZipCode 
WHERE 
    (
      Firmen.State = ''
   OR Firmen.State IS NULL )

See what that gets you. If your get results with values in both columns then you probably have a different issue. However, I am guessing that one of the columns is null or empty since you are updating rows but nothing is changed.

Then there has to be nothing wrong with your query. I think it might be with your update then. Try making the table an alias, like this:

UPDATE 
    F
SET 
    F.State = Postleitzahlen.State 
FROM
    Postleitzahlen
INNER JOIN 
    Firmen F ON Postleitzahlen.ZipCode = F.ZipCode 
WHERE 
    (
      F.State = ''
   OR F.State IS NULL )
RandomBen
I get two columns, first column always empty, second column (always)filled with values.Anyway, the query runs, i get xx affected results, but there aren't any changes :/any ideas?
hubbl
Check out my update. I think it could be because of the Update not using an aliased value. I feel like I ran into this a few years ago because now when I run updates I always alias the table I am updating. If that doesn't work you can try a subquery. It isn't optimal but it should work. I can give you the code for that if it doesn't work.
RandomBen
It would be nice if u post that query with the subquery, your updated alias-style query also don't workfyi: one field is varchar, the other is nvarchar but i found that this can't be the reason..
hubbl
RI posted the other way to do it below :)
RandomBen
+1  A: 
UPDATE 
    Firmen f
SET 
    f.State = (SELECT p.State FROM Postleitzahlen p WHERE p.ZipCode = f.ZipCode)
WHERE 
    (
      f.State = ''
   OR f.State IS NULL )
RenderIn