如何根据条件从另一个表更新表中的列?

时间:2012-09-11 05:04:51

标签: sql-server subquery sql-update multiple-tables

我有两张桌子

  1. 它包含的学生表(Student_id,school_code,name,year,...)
  2. 它包含的学校表(school_id,School_code,School_name,year 等.....)
  3. 我想根据学校代码和年份使用学校代码表中的school_id列更新学生表中的school_code列。我有五年的数据。所以school_id每年都有所不同。

    我的查询是

    UPDATE Master.Student
       SET school_code=( select school_id from Master.school as sc
      JOIN master.student as st
        ON st.school_code=sc.school_code
     WHERE sc.year=x)
     WHERE st.year=x;
    

    但它没有更新。我收到subquery returns more than one value的错误。

4 个答案:

答案 0 :(得分:16)

为什么要在直接执行此操作时使用子查询?

UPDATE st
  SET st.school_code = sc.school_id 
FROM master.student AS st
  JOIN Master.school AS sc
ON st.school_code = sc.school_code
WHERE sc.year=x
  AND st.year=x;

有关详细信息,请参阅UPDATE (Transact-SQL)

答案 1 :(得分:3)

UPDATE Master.Student
  SET school_code = sc.school_id 
FROM Master.school as sc
WHERE school_code = sc.school_code
  AND year = x
  AND st.year = x;

答案 2 :(得分:1)

尝试此查询

UPDATE student SET school_code = c.school_id  
FROM student t
  INNER JOIN school c 
    ON t.school_code = c.school_code AND t.year = c.year
WHERE c.year=x

答案 3 :(得分:-1)

Update Table B set column name (of table b) =x.column name (from Table A) from    
(    
Select column name from Table A a,Table B b    
where a.Column name=b.column name            
)x    
where Table b.Column name=x.Column name(of Table b)
相关问题