I wrote a very simple procedure. I am deliberately making a mistake in the procedure. but the error is not working. I want to return the error I want with raiserror. but it doesn't even go inside the "if".
ALTER PROCEDURE dene
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO bddksektor ([tcmbkodu], [aktif], [bddksektorkodu])
VALUES ('a', 1, 1)
-- I knowingly made a mistake. normally the 1st parameter is int.
-- I'm entering varchar so that it can enter "if" and return an error. but it doesn't
IF @@ERROR <> 0
BEGIN
RAISERROR('Hata', 16, 1, 61106)
RETURN 61106
END
ELSE
BEGIN
SELECT
[tcmbkodu], [aktif], [bddksektorkodu]
FROM
[dbfactoringtest].[dbo].[bddksektor]
ORDER BY
tcmbkodu ASC
END
SET NOCOUNT OFF
END
SQL Server returns its own error when I run the procedure. It does not return the error I wrote because it does not enter the "if"
Error:
Msg 245, Level 16, State 1, Procedure dene, Line 11 [Batch Start Line 1]
Conversion failed when converting the varchar value 'a' to data type int
As I mention in the comment, use a
TRY...CATCH. For your SQL if the firstINSERTfails the batch will be aborted, and so theIFwon't be entered, because it won't be reached. I also recommend switching toTHROWinstead ofRAISERRORas noted in the documentation:This gives you something like this: