Exactly how to do it depends on the DBMS you are using, but I think something like this should do the trick. Inspired by answers to this question.
UPDATE table2
SET table2.firstname = table1.firstname
FROM table1, table2
WHERE
table1.lastname = table2.lastname AND
table1.firstname LIKE CONCAT(table2.firstname, '%')
The WHERE
conditions finds a match in table1
that has the same lastname
as in table2
, and whos firstname
begins with the same string. CONCAT
is string concatenation, so you would get something looking like 'Bobby' LIKE 'Bob%'
.
Please note, that if there are several matches for one row in table2
(for instance, both Anna Smith and Anastasia Smith matching An... Smith), that row will be updated with both. The last one will be the one who sticks, but which one who happend to be last is pretty much random. To check if you have any cases like that, I think you could run this query:
SELECT table2.firstname, table2.lastname
FROM table1, table2
WHERE
table1.lastname = table2.lastname AND
table1.firstname LIKE CONCAT(table2.firstname, '%')
GROUP BY table2.firstname, table2.lastname
HAVING COUNT(*) > 1
Disclaimar: I have not tested any of this.