SQL Server 2008更新表,其中包含另一个表中的值

时间:2012-12-12 08:29:54

标签: sql sql-server sql-server-2008 join sql-update

您可以在下面看到我的简化数据库模型:

enter image description here

由于错误, Job.location 列中只有空值,其中条目属于某个计划。因此,我想更新与此计划相关联的所有工作,将 Job.location 设置为拥有此计划的用户 Location.name

我尝试了这个SQL查询:

    update dbo.Job set location =

        (select name from dbo.Location as loc where

           loc.objectid = objectid  and loc.user_id in 

           (select userid from dbo.[Plan] as p where p.planid = 20))

        where planid = 20

但是,结果总是: 0行受影响。子查询本身可以正常工作。

如何实现具有特定计划的所有作业都受到影响?

2 个答案:

答案 0 :(得分:5)

我认为您错误可能是您在子查询objectid中没有loc.objectid = objectid列的别名,所以当您自己运行子查询时,它就像loc.objectid = loc.objectid一样运行并且当您运行时它在更新中,就像loc.objectid = dbo.Job.objectid

一样

在您的架构中,可以为用户提供多个位置,但假设每个用户和对象只有一个位置,您可以尝试以下查询:

update dbo.Job set
    location = L.Name
from dbo.Job as J
    inner join dbo.[Plan] as P on P.planid = J.planid
    inner join dbo.Location as L on L.user_id = P.userid and L.objectid = J.objectid

答案 1 :(得分:1)

UPDATE
j
SET Job.location = loc.name
FROM
Job j
INNER JOIN Plan p ON j.planid = p.planid
INNER JOIN aspnet_Users u ON p.userid = u.UserId
INNER JOIN Location loc ON u.UserId = loc.user_id
WHERE j.planid = 20 
AND p.planid = 20