2017-02-06 52 views
0

當前正在使用Microsoft SQL Server 2012(Management Studio),希望用使用來自其他表格的數據的查詢更新表格中的列。用多個表格的結果更新表格

這是查詢我運行:

SELECT   
    tblGeneralVehicleInformation.EngineerVehicleReg, tblModel.Model_ID, 
    tblModel.VanOrCar, tblModel.Model, tblMake.Make_ID, 
    tblMake.WarrantyCars, tblMake.WarrantyVans, 
    tblMake.WarrantyCarMonths, tblMake.WarrantyVanMonths, 
    tblGeneralVehicleInformation.PurchaseDate, 
    tblGeneralVehicleInformation.Mileage 
FROM    
    tblGeneralVehicleInformation 
INNER JOIN 
    tblModel ON tblGeneralVehicleInformation.Model_IDFK = tblModel.Model_ID 
INNER JOIN 
    tblMake ON tblGeneralVehicleInformation.Make_IDFK = tblMake.Make_ID 


UPDATE dbo.tblGeneralVehicleInformation 
SET WarrantyId = '1' 
WHERE (tblModel.VanOrCar = N'Van') 
    AND (Mileage > WarrantyVans) 
    AND (DateDiff("M",PurchaseDate,CURRENT_TIMESTAMP) > WarrantyVanMonths) 

若本作品或者是你不能夠有UPDATE語句中像上面的查詢?

感謝您的幫助

回答

1

您需要將兩者結合到一個語句中。我還建議你開始使用表別名,使你的代碼更具可讀性...

UPDATE v 
SET WarrantyId = '1' 
FROM tblGeneralVehicleInformation v 
    INNER JOIN tblModel mo 
     ON v.Model_IDFK = mo.Model_ID 
    INNER JOIN tblMake ma 
     ON v.Make_IDFK = ma.Make_ID 
WHERE (mo.VanOrCar = N'Van') 
    AND (Mileage > WarrantyVans) 
    AND (DateDiff("M",PurchaseDate,CURRENT_TIMESTAMP) > WarrantyVanMonths)