views:

334

answers:

3

Consider the following Dig, Assume that all the three tables have a column Is_Deleted by default it is set to 0... I want to update Is_Deleted=1 field of Customers table where CustId=2 only when the rows containing CustId=2 and Is_Deleted=1 in Orders and OrderItems Tables... I dont want to use Cascade option.. Any suggestion

alt text

+1  A: 

Ok sounds fine... Do we only set the deleted flag when all the orders and all the order items associated with that customer are deleted, or only if at least 1 item is deleted.

anthonyv
@Anthonyv ya i ll set the deleted flag when all the orders and all the order items associated with that customer are deleted
Pandiya Chendur
+1  A: 

Easiest way is EXISTS. I assume you want to check both Orders and OrderItems. This also means you only filter on CustID once.

UPDATE
   C
SET
   IsDeleted = 1
FROM
   Customers C
WHERE
   C.CustID = 2
   AND
   EXISTS (SELECT *
        FROM
            Orders O
        WHERE
            O.CustID = C.CustID AND O.IsDeleted = 1)
   AND
   EXISTS (SELECT *
        FROM
            Orders O
            JOIN
            OrderItems OI ON O.OrderID = OI.OrderID
        WHERE
            O.CustID = C.CustID AND OI.IsDeleted = 1)
gbn
@gbn that works what happens if some rows in orderitems table has Is_Deleted=0 for C.CustID = 2
Pandiya Chendur
Nothing. The EXISTS is false
gbn
A: 

You can make the use of Triggers on Table - Customers

You can get details about triggers :

With Trigger you can check the Value of Updated column and depending on it you can update the data of different tables.

Shivkant