2

Below you can see my simplified DB model:

enter image description here

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?

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works! Just had to add 'where J.planid = 20' in the last row.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.