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 . Therefore I want to update all Jobs associated with this Plan, setting Job.location to Location.name of the User , who owns this Plan.
I tried this SQL query:
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 . The subqueries itself work correctly.
How can I achieve that all Jobs with a certain planid are affected?
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
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
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.