SQL不接受负数proc

时间:2014-05-02 01:51:56

标签: sql-server tsql stored-procedures

我有一个接受5个参数的过程,它需要将描述设置为空字符串,将dateadded设置为currentdate(我使用GETDATE)。但我似乎无法工作的是我需要listprice和折扣百分比在尝试输入负数时抛出错误。我的代码有效,但当我尝试输入负数时,我的陈述没有出现错误。

USE MyGuitarShop;
GO
IF OBJECT_ID('spInsertProduct') IS NOT NULL
DROP PROC spInsertProduct;
GO
CREATE PROC spInsertProduct 
@insCatID int = 0,
@insProdCode varchar(10) = 0,
@insProdName varchar(50) = 0,
@insListPrice money = 0,
@insDisPercent money = 0

AS
IF @insListPrice < 0 
PRINT 'this column does not accept negative numbers';
IF @insDisPercent < 0
PRINT 'this column does not accept negative numbers';

UPDATE Products
SET Description = '', DateAdded = GETDATE();
SELECT CategoryID, ProductCode, ProductName, ListPrice, DiscountPercent
FROM Products

USE MyGuitarShop;
GO

EXEC spInsertProduct
-7,'254-652','Guitar', -300.01, 30.00;

1 个答案:

答案 0 :(得分:2)

您可以在此处使用RAISERRORRETURN进行错误处理。 RAISERROR将生成错误消息,RETURN语句将强制终止,如下所示:

IF @insListPrice < 0 
 BEGIN
 RAISERROR(N'List Price cannot be negative',16,1)
 RETURN
END
IF @insDisPercent < 0 
 BEGIN
 RAISERROR(N'Discount percentage cannot be negative',16,1)
 RETURN
END