使用多个表的结果更新表

时间:2017-02-06 11:07:41

标签: sql-server-2012 sql-update

目前正在使用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 个答案:

答案 0 :(得分: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)