SQL Update SET子查询?

时间:2015-05-28 16:47:03

标签: sql sql-server

我有一个像这样的SQL查询:

UPDATE ScheduleTasks  
SET 
AssignedResource='360 CLEAN'
WHERE (ScheduleID = (SELECT ScheduleID FROM Schedule WHERE Job_No = 'ABC123')) 
AND Description = 'Filing'

我的问题是,我有一个名为Resource的表Resource_IDResource_Name我想要做的是用{{1}更新scheduleTasks表而Resource_ID不是Resource_Name360 CLEAN而不是Resource_Name我的问题是如何从{{1}获得Resource_ID }}

3 个答案:

答案 0 :(得分:4)

您可以在INNER JOIN语句中使用UPDATE执行此操作,如下所示:

UPDATE st SET
    AssignedResource = r.Resource_ID
FROM ScheduleTasks st
    -- change join conditions to your preference
    INNER JOIN Resource r on r.Resource_Name = '360 CLEAN'     
WHERE st.Description = 'Filing' AND EXISTS
(
    SELECT s.ScheduleID 
    FROM Schedule s
    WHERE s.Job_No = 'ABC123' AND st.ScheduleID = s.ScheduleID
)

同时更新了您的查询,以便检查ScheduleID表中是否存在来自ScheduleTasks的{​​{1}}。

答案 1 :(得分:2)

尝试使用sortx

sub-query

答案 2 :(得分:0)

如果要更新ScheduleTasks(我推荐)中的所有记录,请使用:

UPDATE ST
SET AssignedResource = R.Resource_ID
FROM ScheduleTasks ST
  INNER JOIN Resource R ON R.Resource_Name = ST.AssignedResource 

如果要限制更新内容,请添加WHERE子句,如下所示:

UPDATE ST
SET AssignedResource = R.Resource_ID
FROM ScheduleTasks ST
  INNER JOIN Resource R ON R.Resource_Name = ST.AssignedResource 
  INNER JOIN Schedule S ON S.ScheduleID = ST.ScheduleID 
WHERE ST.AssignedResource = '360 CLEAN'
   AND ST.Description = 'Filing'
   AND S.Job_No = 'ABC123'