您可以通过在验证失败时强制出现错误条件来做到这一点,前提是这不是可能自然发生的错误。当您知道某个错误只能在验证失败时发生时,您可以通过检查 catch 块中的 error_number 以自定义方式处理该错误。tempdb 中的示例:
USE tempdb;
GO
CREATE FUNCTION dbo.fXample(@i INT)
RETURNS TINYINT
AS
BEGIN
RETURN (SELECT CASE WHEN @i < 10 -- change this to your "validation failed" condition
THEN 1/0 -- something that will generate an error
ELSE (SELECT @i) -- (you'd have your actual retrieval code here)
END);
END
GO
CREATE PROCEDURE dbo.spXample
@i INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT dbo.fXample(@i);
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 8134 -- divide by zero
BEGIN
THROW 50001, 'Your custom error message.', 1;
-- you can throw any number > 50000 here
END
ELSE -- something else went wrong
BEGIN
THROW; -- throw original error
END
END CATCH
END
GO
现在试试看:
EXEC dbo.spXample @i = 10; -- works fine
EXEC dbo.spXample @i = 6; -- fails validation
EXEC dbo.spXample @i = 256; -- passes validation but overflows return
结果:
----
10
消息 50001,级别 16,状态 1,过程 spXample,第 12 行
您的自定义错误消息。
消息 220,级别 16,状态 2,过程 spXample,第 7 行
数据类型 tinyint 的算术溢出错误,值 = 256。