简体   繁体   中英

UPDATE FROM WHERE Subquery SQL Server

How can I use a subquery from an UPDATE statement? Here is my query:

UPDATE car_availability
SET    availability_status = 'GOOD'
FROM   car_trip AS TRIP
WHERE  car_availability.car_no = TRIP.car_no 
AND NOT EXISTS (SELECT DISTINCT A.car_No 
                FROM   car_maintenance A 
                WHERE  A.car_no = TRIP.vehicle_id 
                AND    start_date = TRIP.workday)
AND EXISTS (SELECT DISTINCT B.car_No 
            FROM   car_maintenance B 
            WHERE  B.car_no = TRIP.vehicle_id 
            AND end_date IS NOT NULL)

I get an error 'FROM clause in UPDATE and DELETE statements cannot contain subquery sources or joins.'

I want to update availability_status to GOOD in which car exists in car_maintenance with its start_date is equal to workday of car_trip and cars which is in car_maintenance with its end date is not null.

As @McNets said, you need to add the car_availability table to your FROM clause. Try this:

UPDATE CA
SET    availability_status = 'GOOD'
FROM   car_availability CA
JOIN car_trip AS TRIP ON CA.car_no = TRIP.car_no 
WHERE NOT EXISTS (SELECT DISTINCT A.car_No 
                FROM   car_maintenance A 
                WHERE  A.car_no = TRIP.vehicle_id 
                AND    start_date = TRIP.workday)
AND EXISTS (SELECT DISTINCT B.car_No 
            FROM   car_maintenance B 
            WHERE  B.car_no = TRIP.vehicle_id 
            AND end_date IS NOT NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM