I have 3 tables BusStop, BusRoute, and Stop_Route (for M-2-M relation). Some stops do not have relation (routes), and I need to update each record in BusStop table with Bit value 1 or 0, depending on whether it has relation or not. I have a query to select all stops which have no relations:
SELECT
BusStop.StopId
FROM
BusStop
LEFT OUTER JOIN BusStop_BusRoute
ON BusStop.StopId = BusStop_BusRoute.StopId
WHERE
BusStop_BusRoute.StopId IS NULL
but I don't clearly understand how to add a value based on this result. I've read about CURSOR and CASE WHEN statements, but I still can't figure out how to apply them in my case. There is a StopStatus column type of Bit where I need to insert that value.
UPDATE BusStop
SET StopStatus =
CASE
WHEN BusStop_BusRoute.StopID IS NULL THEN 0
ELSE 1
END
FROM
BusStop
LEFT JOIN BusStop_BusRoute
ON BusStop.StopId = BusStop_BusRoute.StopId
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With