简体   繁体   中英

Update statement in sql server 2005

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

替代文字
(source: microsoft.com )

确定听起来不错...仅在删除与该客户关联的所有订单和所有订单项目时,或者仅在删除至少一项时,才设置删除标志。

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)

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.

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