可以将更新命令合并到一个命令中吗?

时间:2017-09-18 10:30:08

标签: sql sql-server

我需要帮助,下面是否可以将所有三个更新命令合并到一个具有所有条件的更新命令中? 请提供对我有帮助的任何样本。

    UPDATE T1 
    SET STRING2 = I.ResultString, 
        CS_ATTR_020 = I.masonStatus,
        CLASSIFICATION = I.newClassification 
    FROM DOC T1 
    INNER JOIN #InsertedTempTable I ON T1.DB_ZZ_ID=I.ZZ_ID --T1.DOC_KEY=I.docKey AND T1.REVISION=I.docRevision


   UPDATE T3 
   SET CS_ATTR_020 = 2,  
       STRING2 = REPLACE(STRING2, 'RELEASED', 'OBSOLETE') 
    FROM DOC T3 
    INNER JOIN  #InsertedTempTable I ON T3.DB_ZZ_ID=I.ZZ_ID  --T3.DOC_KEY=I.docKey AND  T3.REVISION=I.docRevision
    WHERE STATUS = 7 and OBSOLETE = 1 and CS_ATTR_020 <> 2   AND STRING2 LIKE 'RELEASED%' 

  UPDATE T4  
  SET CS_ATTR_020 = 1,  
      STRING2 = REPLACE(STRING2, 'OBSOLETE', 'RELEASED') 
  FROM DOC T4 
  INNER JOIN  #InsertedTempTable I ON T4.DB_ZZ_ID=I.ZZ_ID    --T4.DOC_KEY=I.docKey AND  T4.REVISION=I.docRevision
  WHERE STATUS = 7 and OBSOLETE = 0 and CS_ATTR_020 = 2  AND STRING2 LIKE 'OBSOLETE%' 

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

由于您要更新三个更新语句中的同一个表,因此您可以使用CASE表达式在一个更新查询中执行此操作,如下所示:

UPDATE t
SET CS_ATTR_020 = CASE WHEN STATUS = 7 and OBSOLETE = 1 and CS_ATTR_020 <> 2   AND STRING2 LIKE 'RELEASED%' THEN 2  
                       WHEN STATUS = 7 and OBSOLETE = 0 and CS_ATTR_020 = 2  AND STRING2 LIKE 'OBSOLETE%'   THEN 1
                       ELSE I.masonStatus END,
    STRING2 = CASE WHEN STATUS = 7 and OBSOLETE = 1 and CS_ATTR_020 <> 2   AND STRING2 LIKE 'RELEASED%' THEN REPLACE(STRING2, 'RELEASED', 'OBSOLETE') 
                   WHEN STATUS = 7 and OBSOLETE = 0 and CS_ATTR_020 = 2  AND STRING2 LIKE 'OBSOLETE%' THEN REPLACE(STRING2, 'OBSOLETE', 'RELEASED') 
    ELSE I.ResultString END,
    CLASSIFICATION = CASE WHEN (STATUS = 7 and OBSOLETE = 1 and CS_ATTR_020 <> 2   AND STRING2 LIKE 'RELEASED%')
                               OR (STATUS = 7 and OBSOLETE = 0 and CS_ATTR_020 = 2  AND STRING2 LIKE 'OBSOLETE%' )
                        THEN t.CLASSIFICATION ELSE I.newClassification END
FROM DOC AS T
INNER JOIN  #InsertedTempTable I ON T.DB_ZZ_ID=I.ZZ_ID;