多个Join,Multiple where语句和多个更新

时间:2015-07-07 04:54:51

标签: sql sql-server-2012

您好我做了2次查询来更新一些数据。但我需要让它变得更简单。而不是进行2次查询,我需要进行一次查询。和我使用的连接,我只需要使用它一次。任何人都可以帮助我:

当前查询:

USE DB02
GO

UPDATE TCC  
SET RANK = 'S'
FROM TOTAL_NEGO_HISTORY TNH 
    JOIN M_CONTRACT MC                  ON TNH.CONTRACT_ID = MC.CONTRACT_ID
    JOIN T_DEPOSIT_ASSIGNED_LIST TDAL   ON TDAL.CONTRACT_ID = MC.CONTRACT_ID 
    JOIN T_DEPOSIT_HISTORY TDH          ON TDH.DEPOSIT_NO = TDAL.DEPOSIT_NO
    JOIN T_CREDIT_CONTRACT TCC          ON TCC.CONTRACT_ID = MC.CONTRACT_ID
WHERE TDH.DEPOSIT_YMD = TNH.COMMITMENT_DATE
GO


UPDATE TCC
SET RANK = 'C2'
FROM TOTAL_NEGO_HISTORY TNH  
    JOIN M_CONTRACT MC                  ON TNH.CONTRACT_ID = MC.CONTRACT_ID
    JOIN T_DEPOSIT_ASSIGNED_LIST TDAL   ON TDAL.CONTRACT_ID = MC.CONTRACT_ID 
    JOIN T_DEPOSIT_HISTORY TDH          ON TDH.DEPOSIT_NO = TDAL.DEPOSIT_NO
    JOIN T_CREDIT_CONTRACT TCC          ON TCC.CONTRACT_ID = MC.CONTRACT_ID
WHERE TDH.DEPOSIT_MONEY = TNH.COMMITMENT_AMAOUNT
GO

预计会有类似下面的事情:

USE DB02
GO

UPDATE TCC  
SET RANK = 'S'  case WHEN TDH.DEPOSIT_YMD = TNH.COMMITMENT_DATE 
SET RANK = 'C2' case WHEN TDH.DEPOSIT_MONEY = TNH.COMMITMENT_AMAOUNT
FROM TOTAL_NEGO_HISTORY TNH 
    JOIN M_CONTRACT MC                  ON TNH.CONTRACT_ID = MC.CONTRACT_ID
    JOIN T_DEPOSIT_ASSIGNED_LIST TDAL   ON TDAL.CONTRACT_ID = MC.CONTRACT_ID 
    JOIN T_DEPOSIT_HISTORY TDH          ON TDH.DEPOSIT_NO = TDAL.DEPOSIT_NO
    JOIN T_CREDIT_CONTRACT TCC          ON TCC.CONTRACT_ID = MC.CONTRACT_ID
GO

1 个答案:

答案 0 :(得分:1)

USE DB02
GO

UPDATE  TCC  
SET     RANK = (Case WHEN TDH.DEPOSIT_YMD = TNH.COMMITMENT_DATE Then 'S'
                    WHEN TDH.DEPOSIT_MONEY = TNH.COMMITMENT_AMAOUNT Then 'C2'
                    Else RANK   ----there should be else to handle case when properly
              End)
FROM    TOTAL_NEGO_HISTORY TNH 
        JOIN M_CONTRACT MC                  ON TNH.CONTRACT_ID = MC.CONTRACT_ID
        JOIN T_DEPOSIT_ASSIGNED_LIST TDAL   ON TDAL.CONTRACT_ID = MC.CONTRACT_ID 
        JOIN T_DEPOSIT_HISTORY TDH          ON TDH.DEPOSIT_NO = TDAL.DEPOSIT_NO
        JOIN T_CREDIT_CONTRACT TCC          ON TCC.CONTRACT_ID = MC.CONTRACT_ID
GO