I’ve got two tables in a database with the following columns:
Table1
athleteId | sportTypeId
205 | 5
206 | 5
206 | 6
207 | 4
208 | 1
208 | 4
Due to an error I made (whoops), the second table has some information like this:
Table2*
athleteId | sportTypeId
205 | 4
206 | 4
207 | 4
208 | 4
NULL | 4
I assigned the wrong athleteId to some athletes, so what I need to do is check every row in Table2 and see if it has a matching row in Table1. The rows containing athleteId 205 and 206 from Table2 would have the athleteId set to NULL (they don’t have a sportTypeId of 4 in Table1). athleteId 207 and 208 would remain (they do have a row in Table1 with sportTypeId of 4).
Notice that some athletes appear twice in Table1.
I’m using SQL Server 2008.
Thanks!
Just to be clear, you’re asking for a way to delete rows from
Table2where there is no matching row inTable1, correct? If so, here’s how to do it:The reason this works is because of the left join and the where clause. The left join will cause
t1.athleteIdto be null whenever a matching record isn’t found inTable1.Edit: If you just want to set the
athleteIdto null instead of deleting the whole row, it’s a small modification: