如何使用多值更新

时间:2012-02-22 08:38:38

标签: sql-server

我有一张表TeacherTeacherID, value1, value2

我需要像这样更新价值:我致电temptableTeacherID, value1, value2

TeacherID  Value1 Value2
T01       | 9    | 9
T01       | 19   | 8
T02       | 10   | 10

值需要更新,它有2行,具有相同的TeacherID。我希望T01的行具有新值19

我写了这样的UPDATE:

update Teacher   
set  Teacher.value1 = proco.ProCoName,   
     Teacher.value2 = proco.Co    
from (select tempTechID, tempvalue1, tempvalue2 from temptable) tmp
where Teacher.TeacherID = tmp.tempTechID

但是当我执行这个SQL时,TeacherID = T01行的值变为9

任何人都可以帮助我吗?谢谢大家。

1 个答案:

答案 0 :(得分:1)

您需要在where子句中使用的条件上使用唯一行,否则您可能会更新您不想要的一行或多行。

编辑:添加了黑客方式的代码。

update Teacher   
set Teacher.value1 = proco.ProCoName,   
    Teacher.value2 = proco.Co    
from (SELECT ROW_NUMBER() OVER(ORDER BY value1) [RN],
         teacherID, value1, value2
  FROM Teacher )
INNER JOIN (select  ROW_NUMBER() OVER(ORDER BY tempvalue1) [TMPRN],
        tempTechID,tempvalue1,tempvalue2 
            from temptable) tmp
ON teacher.RN = tmp.TMPRN

或者您可以构建临时表以获得教师ID和前两个值,然后将两个新值连接回以前的值并将列设置为新值。

INSERT INTO #tempData
SELECT teacherID, value1, value2, newvalue1, newvalue2
FROM teacher

UPDATE Teacher
SET value1 = newvalue1, value2 = newvalue2
FROM Teacher t
INNER JOIN #tempData td
ON t.teacherid = td.teacherID
AND t.value1 = td.value1
AND t.value2 = td.value2