You can do this by forcing an error condition when your validation fails, provided that it is not a possible error that can occur naturally. When you know that a certain error can only occur if the verification fails, you can handle it in your own way by checking this error_number in your catch block. Example in tempdb:
USE tempdb; GO CREATE FUNCTION dbo.fXample(@i INT) RETURNS TINYINT AS BEGIN RETURN (SELECT CASE WHEN @i < 10
Now try:
EXEC dbo.spXample @i = 10; -- works fine EXEC dbo.spXample @i = 6; -- fails validation EXEC dbo.spXample @i = 256; -- passes validation but overflows return
Results:
Msg 50001, Level 16, State 1, spXample Procedure, Line 12
Your custom error message.
Msg 220, Level 16, State 2, spXample Procedure, Line 7
Arithmetic overflow error for tinyint data type, value = 256.
source share