[英]problem with raiseerror()
what I want to do is to create a stored procedure that executes insert statement.There is a possibility the execution to fail because of a check constraint for the table Employee.In that case I want to handle a user-defined error.Obviously the following procedure is not working properly because it always raises my error,but not only when insertion fails.我想要做的是创建一个执行插入语句的存储过程。由于表 Employee 的检查约束,执行可能会失败。在这种情况下,我想处理用户定义的错误。显然以下程序无法正常工作,因为它总是会引发我的错误,但不仅是在插入失败时。
EXEC sp_addmessage 50001, 16, N'Title must be one of the following - Captain,Engineer,Flight-attendant,Purser,First-officer';
CREATE PROCEDURE InsertIntoEmployee
@firstName nvarchar(30),
@familyName nvarchar(30),
@title nvarchar(50),
@address nvarchar(50),
@chiefID int ,
@salary money ,
@FK_IDCrew int,
@FK_DepartmentID int
AS
BEGIN
declare @err_num int;
declare @err_sev int;
declare @err_msg int;
begin try
insert into Employee(firstName, familyName, title, address, chiefID, salary, FK_IDCrew,
FK_DepartmentID)
values(@firstName, @familyName, @title, @address, @chiefID, @salary, @FK_IDCrew,
@FK_DepartmentID);
raiserror(50001,16,1);
END try
begin catch
set @err_num=ERROR_NUMBER();
set @err_sev=ERROR_SEVERITY();
set @err_msg=ERROR_STATE();
raiserror(@err_num,@err_sev,@err_msg);
end catch
end
GO
In this case:在这种情况下:
Your code will also always hit the RAISERROR too which doesn't add any value,您的代码也总是会遇到 RAISERROR ,这不会增加任何价值,
I hope that the dimensions mentioned in the parameter list is sycn with table columns length.我希望参数列表中提到的维度是带有表列长度的sycn。
Before insertion , You should check take care of following points.在插入之前,您应该检查以下几点。
Check the existence of @FK_IDCrew value in it's table.检查其表中是否存在@FK_IDCrew值。
Check the existence of @FK_DepartmentID value in it's table.检查其表中是否存在@FK_DepartmentID值。
It should be like below.它应该如下所示。
If Not Exists(Select IDCrewColumnName From Table Where columnName = @FK_IDCrew)
Begin
return here from the stored procedure.
End
In case any of them fails to meet the conditions, you should show some user friendly message to user that如果其中任何一个不符合条件,您应该向用户显示一些用户友好的消息
(a) Crew ID , you are going to insert, either deleted or does not exists in the database. (a) Crew ID ,你要插入的,要么已删除,要么在数据库中不存在。
(b) DepartmentID , you are going to insert, either deleted or does not exists in the database. (b) DepartmentID ,您要插入,已删除或在数据库中不存在。
In this way the probability of error will also come to an end.这样,出错的概率也将结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.