SQL Server:根据同一表中另一列与另一表的匹配值,更新一个表中某列的值';s柱
以下是我面临的困境:SQL Server:根据同一表中另一列与另一表的匹配值,更新一个表中某列的值';s柱,sql,sql-server-2008,Sql,Sql Server 2008,以下是我面临的困境: table1有列employee,employeeID table2有列uniqueEmployeeName,id table1对employeeID到table2,id的主键有外键约束 table1中的列employee可以匹配table2中的uniqueEmployeeName的一个值 table1中的employeeID列当前为空,我想根据table2中的employeename匹配table1中的employeeID到table2中的uniqueEmployeeN
有列employee,table1
employeeID
有列table2
,uniqueEmployeeName
id
对table1
到employeeID
,table2
的主键有外键约束id
中的列table1
可以匹配employee
中的table2
的一个值uniqueEmployeeName
中的table1
列当前为空,我想根据employeeID
中的table2
匹配employeename
中的table1
到employeeID
中的table2
来更新它uniqueEmployeeName
update table1
set table1.employeeID = (select distinct id
from table2
where uniqueEmployeeName = table1.employee)
问题是查询只是无休止地运行,所以我不确定我的查询在哪里出了问题。有人能看出我的逻辑哪里出错了吗
下面是一个示例,说明了“之前”和“之后”应该是什么样子:
之前:
table1 table2
employee employeeID uniqueEmployeeName id
bob peter 1
saget pipper 2
saget 3
bob 4
之后:
table1 table2
employee employeeID uniqueEmployeeName id
bob 4 peter 1
saget 3 pipper 2
saget 3
bob 4
若表1中的记录太多,可以在update语句中使用TOP()。内部连接也应该有帮助
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
你们的桌子有多大?它是否仍在运行,或者是否终止了查询?如果您有非常大的表,您可能只需要让这个查询运行,直到它完成。