[英]SQL Server 2008 update table with values from another table
Below you can see my simplified DB model: 在下面,您可以看到我的简化数据库模型:
Due to an error there are only null-values in the column Job.location where the entries belong to a certain Plan . 由于错误, Job.location列中只有空值,其中条目属于某个Plan 。 Therefore I want to update all Jobs associated with this Plan, setting Job.location to Location.name of the User , who owns this Plan.
因此,我想更新与此计划关联的所有作业,将Job.location设置为拥有该计划的User的 Location.name 。
I tried this SQL query: 我试过这个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
However, the result is always: 0 rows affected . 但是,结果始终是: 0行受影响 。 The subqueries itself work correctly.
子查询本身可以正常工作。
How can I achieve that all Jobs with a certain planid are affected? 我如何才能确保所有具有特定Planid的工作都受到影响?
I think you mistake may be that you have no alias for objectid
column in subquery loc.objectid = objectid
, so when you running subquery by itself, it just works like loc.objectid = loc.objectid
and when you running it in the update, it works like loc.objectid = dbo.Job.objectid
我认为您的错误可能是您在子查询
loc.objectid = objectid
没有objectid
列的别名,因此当您loc.objectid = objectid
运行子查询时,它就像loc.objectid = loc.objectid
一样工作,并且在更新中运行它时,它的工作方式类似于loc.objectid = dbo.Job.objectid
In your schema it's possible to have multiple locations for users, but supposing you have only one location per user and object, you can try this query: 在您的模式中,可能有多个用户位置,但是假设每个用户和每个对象只有一个位置,则可以尝试以下查询:
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.