I'm trying to update a column in a table based on another column in another table.
UPDATE eval e
SET rank = (SELECT p.desc
FROM Position p
WHERE p.id = e.faculty
AND p.date >= '2011-05-20'
)
p.id
and e.faculty
correspond. I want to update rank with p.desc
if the id's are the same. (e.faculty
and p.id
)
Any help will be great! :)
Try this for SQL Server:
UPDATE dbo.eval
SET rank = p.desc
FROM dbo.Position p
WHERE p.id = eval.faculty and p.date >= '2011-05-20'
or if you need an alias on the base table (for whatever reason), you need to do this:
UPDATE dbo.eval
SET rank = p.desc
FROM dbo.eval e
INNER JOIN dbo.Position p ON p.id = e.faculty
WHERE p.date >= '2011-05-20'
You need a restriction in the form of a WHERE
clause; if you use EXISTS
you can based it on you scalar subquery e.g.
UPDATE eval
SET rank = (
SELECT p.desc
FROM Position p
WHERE p.id = eval.faculty
AND p.date >= '2011-05-20'
)
WHERE EXISTS (
SELECT *
FROM Position p
WHERE p.id = eval.faculty
AND p.date >= '2011-05-20'
);
Note the above targets the UPDATE
on the base table eval
rather than the correlation name e
. This makes a lot more sense when you think of an SQL UPDATE
in terms of relational assignment i.e. you don't want to assign to e
because it (unlike the base table) will go out of scope!