【问题标题】:Create a function to check if the quantity inserted is greater than the quantity in stock创建一个函数来检查插入的数量是否大于库存数量
【发布时间】:2017-12-28 08:26:07
【问题描述】:
CREATE TABLE [dbo].[OrderDetails](
    [OrderID] [int] NOT NULL,
    [ProductID] [int] NOT NULL,
    [UnitPrice] [int] NOT NULL,
    [Quantity] [tinyint] NULL,
    [Discount] [int] NULL,
    [IsActive] [bit] NULL,
    [IsDeleted] [bit] NULL
) ON [PRIMARY]

我想创建一个函数来检查插入的数量是否大于库存数量然后阻止用户执行。

【问题讨论】:

  • 想想哪个SELECT 会给你正确的回应......然后将它添加到你的应用中。

标签: sql function stored-procedures triggers


【解决方案1】:

设置 QUOTED_IDENTIFIER ON; 去吧

创建触发器 dbo.PreventQtyInsert ON dbo.OrderDetails 插入后 作为 开始 声明 @returnQuantity INT , @数量 INT , @ProductID INT , @GetQuantityFromProductsTable INT;

    SELECT @returnQuantity = dbo.ReturnUnitsInStock ( @Quantity , @ProductID ) ;

    IF @returnQuantity = 0
        BEGIN
            RAISERROR ( 'This vendor''s credit rating is too low to accept new purchase orders.' , 16 , 1 ) ;
            ROLLBACK TRANSACTION;
            RETURN;
        END;
    ELSE
        BEGIN

            SET @GetQuantityFromProductsTable = ( SELECT UnitsInStock FROM Products WHERE ProductID = @ProductID ) ;
            UPDATE OrderDetails SET Quantity = @GetQuantityFromProductsTable - @Quantity
            WHERE ProductID = @ProductID;


        END;

END;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多