Thursday, 18 September 2008

Preventing Statements Outside Transactions

In some cases you may need to prevent statements or sub-stored-procedures from being executed either outside of a transaction or directly in code or Query Analyzer; thus ensuring that a developer doesn't accidentally create the scenario where a 2-phase-commit can be breached. The following snippets will help with that.

-- ensure we are inside a transaction
-- otherwise throw a message and end
BEGIN TRAN TransactionSample
if (@@trancount = 0)
begin
print 'This Procedure Must Be Called From a Transaction'
return
end
else
begin
print 'Called From Transaction'
return
end
COMMIT TRAN TransactionSample


-- ensure the statements is called from within
--atleast 1 stored procedure and not in QA or code
if (@@nestlevel = 0)
begin
print 'This Proc Must Not Be Called Directly!'
end

else

begin
print 'Called From Stored Procedure'
end


Of course, they can be combined :)