I am writing a stored procedure in sql server 2008. The problem is the @ErrorMessage out parameter is always null. It seems to be related to the ERROR_MESSAGE() function, because when I get rid of that the other part of the message is returned.
How can I get it to return the entire errorMessage?
-- Log transaction
INSERT INTO Transactions (TxnId, TypeId, [Date], Amount)
VALUES(@TxnId, @TypeId, @TransDate, @Amount)
-- Check for errors
IF @@ERROR <> 0
BEGIN
PRINT 'Starting third error block'
SET @ErrorCode = 202
SELECT @ErrorMessage = 'Err_TxnId_Exists - Error inserting: ' + ERROR_MESSAGE()
PRINT @ErrorCode
PRINT @ErrorMessage
PRINT 'Ending third error block'
RETURN 1
END
Messages output
The statement has been terminated. Starting third error block 202
Ending third error block
(1 row(s) affected)
Results
(1 row(s) affected)
Using @@ERROR to conditionally exit a procedure. The following example uses IF...ELSE statements to test @@ERROR after an DELETE statement in a stored procedure. The value of the @@ERROR variable determines the return code sent to the calling program, indicating success or failure of the procedure.
Retrieving Error InformationERROR_STATE() returns the error state number. ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred. ERROR_LINE() returns the line number inside the routine that caused the error. ERROR_MESSAGE() returns the complete text of the error message.
When called in a CATCH block, ERROR_MESSAGE returns the complete text of the error message that caused the CATCH block to run. The text includes the values supplied for any substitutable parameters - for example, lengths, object names, or times. ERROR_MESSAGE returns NULL when called outside the scope of a CATCH block.
In SQL Server Management Studio (SSMS), expand Programmability > Stored Procedures, right click a stored procedure and select Execute Stored Procedure. In the execute procedure page, enter the parameter @CustID value as 10 and click OK. It returns the following T-SQL statement with a variable @return_value.
ERROR_MESSAGE() is only valid inside a CATCH block.
Give this a shot:
BEGIN TRY
INSERT INTO Transactions (TxnId, TypeId, [Date], Amount)
VALUES (@TxnId, @TypeId, @TransDate, @Amount)
END TRY
BEGIN CATCH
SET @ErrorCode = 202
SET @ErrorMessage = ERROR_MESSAGE()
PRINT @ErrorCode
PRINT @ErrorMessage
END CATCH;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With