简体   繁体   中英

SQL Server: update value of a column in one table based on the matching value of another column in the same table to another table's column

Here's the dilemma that I have:

  • table1 has columns employee, employeeID
  • table2 has columns uniqueEmployeeName , id

  • table1 has a foreign key constraint on employeeID to the primary key of table2 , id .

  • column employee in table1 can match one of the values for uniqueEmployeeName in table2
  • column employeeID in table1 is currently empty, and I would like to update it with table2 's column id based on matching employee in table1 to uniqueEmployeeName in table2 .

This is what I have so far:

update table1 
set table1.employeeID = (select distinct id 
                         from table2 
                         where uniqueEmployeeName = table1.employee)

The issue is that the query just runs endlessly, so I'm not sure where my query has gone wrong for what I want to do. Can anyone see where my logic went wrong?

Here's example of what the before and after should look like:

BEFORE:

table1                                   table2                                
employee      employeeID                 uniqueEmployeeName     id
bob                                      peter                  1
saget                                    pipper                 2
                                         saget                  3
                                         bob                    4

AFTER:

table1                                   table2                                
employee      employeeID                 uniqueEmployeeName     id
bob           4                          peter                  1
saget         3                          pipper                 2
                                         saget                  3
                                         bob                    4

If there are too many records in table1 you can use TOP() in update statement. Inner join should help as well.

declare @rows int
set @rows = 1
while @rows > 0
BEGIN
update top (1000) table1 
set employeeID = table2.id 
from table2 inner join table1 on table2.uniqueEmployeeName = table1.employee
where table1.employeeID is null
-- or table1.employeeID = ""
set @rows = @@ROWCOUNT
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM