Tuesday, August 28, 2007

SQL raising errors as part of transaction

Here is an example of a sql stored procedure with a transaction which can raise an error and return if some condition is met, it will also catch an error from any called procedure and roll-back the transaction if necessary.


BEGIN TRAN

EXEC dbo.some_sql_function @variable

IF(some_condition)
BEGIN
  RAISERROR ('this %s doesn''t exist.', 16, 1, @errordesc)
  RETURN
END

IF (@@ERROR = 0)
BEGIN
  COMMIT TRAN
  SELECT 1
END
ELSE
BEGIN
  ROLLBACK TRAN
  SELECT -1
END

No comments: