Update table based on another table

后端 未结 2 830
北恋
北恋 2020-12-06 03:02

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         


        
相关标签:
2条回答
  • 2020-12-06 03:14

    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'
    
    0 讨论(0)
  • 2020-12-06 03:33

    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!

    0 讨论(0)
提交回复
热议问题