我想要做的是创建一个执行插入语句的存储过程。由于表 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