sqlsql-serverdatabasesql-server-2008dbo

Can't update from NULL to 0


Hi i'm using this command to left join a table with another table that has a little more records but it keep printing NULL. I want that NULL to become 0.

SELECT * FROM TABLE1

Left JOIN Table2 ON TABLE1.ID=Table2.IDRel

UPDATE Table2 SET IDRel = 0 where IDRel = NULL

Solution

  • The update should not be needed. As you said Table2 has a little more records that's the key thing here, that means that for any row from Table1 for which no matching IDRel value could be found that column (IDRel) will stay NULL.

    Now you could for example use ISNULL(IDRel, 0) to replace null value with 0, but maybe an INNER JOIN instead of the LEFT JOIN could get you the right result throwing out all rows that could not be matched...

    However... If you really were to update that column it would only work if you did the correct comparison against NULL (that is IS not =) that would mean changing your update query into:

    UPDATE Table2 SET IDRel = 0 where IDRel IS NULL