USE MYDATABASENAME;
GO
BEGIN
–Begin Work
BEGIN TRY;
BEGIN TRANSACTION
BEGIN
DECLARE @ToBeUpdatedCount INT,
@RecordCount INT
SET @ToBeUpdatedCount = (
/* WRITE SELECT QUERY HERE TO DETERMINE NUMBER OF ROWS THAT SHOULD BE UPDATED */
)
/* WRITE UPDATE QUERY HERE */
SET @RecordCount = @@ROWCOUNT
IF @RecordCount <> @ToBeUpdatedCount
BEGIN
ROLLBACK TRANSACTION;
DECLARE @ErrorText VARCHAR(1000);
SET @ErrorText = ‘Records Updated did not match records selected. ‘
+ CONVERT(VARCHAR,@RecordCount) + ‘ records Updated ‘
+ CONVERT(VARCHAR,@ToBeUpdatedCount) + ‘ records Selected’;
RAISERROR(@ErrorText,17,16);
END
ELSE
BEGIN
COMMIT TRANSACTION
PRINT ‘Records Updated did match records selected. ‘
+ CONVERT(VARCHAR,@RecordCount) + ‘ Updated ‘
+ CONVERT(VARCHAR,@ToBeUpdatedCount) + ‘ records Selected’;
END
END;
END TRY
–Catch errors and return to user
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END
DECLARE @ErrMsg NVARCHAR(4000),
@ErrSeverity INT
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR ( @ErrMsg , @ErrSeverity , 16 )
RETURN
END CATCH
END