2012-09-11 109 views
7

我有兩個表包含如何根據條件從另一個表中更新表中的列?

  1. 學生表(student_id數據,school_code,名稱,年份,...)
  2. 它包含
  3. 校表(學校ID,School_code,School_name,一年 等.. ..)

我想更新與基於學校代碼和今年學校代碼表中的學校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的錯誤。

+0

這是因爲你越來越schoo_id'的'多個值。並顯示你的完整錯誤。 – hims056

+0

沒有任何給定的答案可以幫助你嗎? – hims056

+0

對不起......我的問題解決了......謝謝你的所有 – Pavi

回答

12

爲什麼要使用子查詢時,您可以直接做到這一點?

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
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; 
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 
相關問題