当我在SQL Server 2012中执行我的过程时,为什么我的错误没有开始

时间:2015-04-26 20:29:11

标签: sql sql-server sql-server-2012

这是我的代码:

IF OBJECT_ID('spUpdateProductDiscount') IS NOT NULL
    DROP PROC spUpdateProductDiscount
    GO

CREATE PROC spUpdateProductDiscount
    (@ProductID INT,    @DiscountPercent INT)
AS
BEGIN
    BEGIN TRY 
        UPDATE Products
        SET DiscountPercent = @DiscountPercent
        WHERE ProductID = @ProductID
    END TRY
    BEGIN CATCH
        IF @DiscountPercent <= 0
            PRINT 'The value for this column DiscountPercent must be a positive number';
    END CATCH
END;
EXEC spUpdateProductDiscount 1999, -15.00

我不知道为什么我的PRINT语句没有被踢进去。如果@DiscountPercent小于或等于0,我就把它设置为所以我不明白为什么PRINT 1}}语句没有踢,但它正在将行更改为-15.00的DiscountPercent

2 个答案:

答案 0 :(得分:5)

也许您需要添加约束?

alter table products add constraint chk_discount_percent check (discountpercent > 0)

答案 1 :(得分:2)

替代Gordon提出的添加约束的建议,我们也可以只检查参数。

IF OBJECT_ID('spUpdateProductDiscount') IS NOT NULL
    DROP PROC spUpdateProductDiscount
    GO

CREATE PROC spUpdateProductDiscount
    (@ProductID INT,    @DiscountPercent INT)
AS
BEGIN
    IF @DiscountPercent <= 0 BEGIN
        PRINT 'The value for this column DiscountPercent must be a positive number';
    END ELSE BEGIN
        UPDATE Products
        SET DiscountPercent = @DiscountPercent
        WHERE ProductID = @ProductID
    END
END;