My SQL存储过程中ELSEIF出现异常



我在我的SQL中编写了如下存储过程:


DELIMITER //
CREATE PROCEDURE SP_Add_Expense
(
p_Expense_ID            int /* = null */,
p_Project_ID            int, 
p_Category_ID       int,
p_Sub_Category_ID   int,
p_SupplierID            int,
p_ExpenseDate       datetime,
p_Notes             text/* =null */,
p_Quantity          int,
p_Price             decimal(18,2),
p_CreatedBy         int
)
BEGIN
IF((select count(*) from Expense where Category_ID = p_Category_ID AND Sub_Category_ID = p_Sub_Category_ID 
AND SupplierID = p_SupplierID AND p_Expense_ID IS NULL) > 0)
THEN
THROW 50005, N'Expense already exists!!!', 1
ELSEIF ((select count(*) from Expense where Expense_ID = p_Expense_ID) > 0)
THEN
Update Expense set Category_ID = p_Category_ID, Sub_Category_ID = p_Sub_Category_ID, SupplierID = p_SupplierID, Quantity = p_Quantity, ExpenseDate = p_ExpenseDate,
Notes = p_Notes, Price = p_Price, ModifiedBy = p_CreatedBy, ModifiedDate = NOW(), Project_ID= p_Project_ID where Expense_ID = p_Expense_ID;
ELSE
INSERT INTO Expense (Project_ID, Category_ID, Sub_Category_ID, SupplierID, Quantity, Price, CreatedBy, CreatedDate, ExpenseDate, Notes)
VALUES (p_Project_ID, p_Category_ID, p_Sub_Category_ID, p_SupplierID, p_Quantity, p_Price, p_CreatedBy, NOW(), p_ExpenseDate, p_Notes);
END IF;
END IF;
END;
//
DELIMITER ;

它正在向ELSEIF抛出异常。异常逻辑就像如果我得到的支出计数大于0,我就会抛出异常,就像它已经存在一样。不明白什么是错误。

这是无效的MySQL语法:

THROW 50005, N'Expense already exists!!!', 1

这看起来像SQL Server。在MySQL中,可以使用SIGNAL从代码块中引发异常,例如:

SIGNAL SQLSTATE '50005' SET MESSAGE_TEXT = 'Expense already exists!!!';

您应该使用SIGNAL,而不是THROW。

最新更新