I'm writing a stored procedure that needs to clean up some data if an insert
fails. I'd like it to perform the clean up, but return the original error if this insert fails (primarily for logging as I want to see exactly why the insert
failed). Basically like a throw;
in C#
. Is there a simple way to do this?
BEGIN TRY
Insert into table (col1) values ('1')
END TRY
BEGIN CATCH
--do clean up here
--then throw original error
END TRY
Is this feasible/good practice? In the application code that calls the proc, I'm handling the error from an application standpoint, but the clean up statements seem to better fit inside the proc.
Try the following snippet.
DECLARE @errNum int
DECLARE @rowCount int
BEGIN TRY
INSERT INTO [TABLE] (COL1) VALUES ('1")
END TRY
BEGIN CATCH
SET @errNum = @@ERROR
SET @rowCount = @@ROWCOUNT
RAISEERROR(@errNum)
END CATCH