简化T-SQL请求

时间:2017-07-29 13:53:57

标签: sql-server tsql triggers sql-insert

所以我在插入触发器中有这个代码。基本上,当我尝试插入atbl_sales_orderlines时,它会检查atbl_sales_products中是否有足够的数量来插入新订单。我想知道这是否可以以更有效的方式完成(可能使用更少的SELECTS)。代码如下:

    BEGIN
        IF (EXISTS (SELECT 1 FROM (
            SELECT x.ProductId, totalOrdersQty, ISNULL(asp.Quantity, 0) PossibleQty FROM (
                SELECT i.ProductId, sum(aso.Amount) totalOrdersQty 
                FROM (SELECT DISTINCT ProductId FROM inserted) i
                JOIN atbl_Sales_OrdersLines aso ON aso.ProductId = i.ProductId
                GROUP BY i.ProductId) x
            LEFT JOIN atbl_Sales_ProductS asp ON asp.ProductId = x.ProductId
            ) x
            WHERE PossibleQty < totalOrdersQty)) 
        BEGIN
            RAISERROR ('Quantity is not sufficient' ,18,1)
            ROLLBACK TRANSACTION
        END
    END

P.S。我知道应该在触发前完成这样的事情。我这样做是为了学习目的。代码有效。

1 个答案:

答案 0 :(得分:2)

虽然不确定性能差异

,但可以简化删除一个派生表
BEGIN 
    IF EXISTS (SELECT 1 
               FROM   atbl_sales_products asp 
               WHERE  EXISTS (SELECT 1 
                              FROM   (select distinct productid from inserted) i 
                                     JOIN atbl_sales_orderslines aso 
                                       ON aso.productid = i.productid 
                              WHERE  asp.productid = x.productid 
                              GROUP  BY i.productid 
                              HAVING Isnull(asp.quantity, 0) < Sum(aso.amount))) 
      BEGIN 
          RAISERROR ('Quantity is not sufficient',18,1) 

          ROLLBACK TRANSACTION 
      END 
END