Skip to content
Advertisement

How to stop insert in a transaction in SQL Server?

Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

my result

Advertisement

Answer

I suppose you’re looking for using @@ROWCOUNT instead of @@TRANCOUNT

If you really want to use nested transactions and use @@TRANCOUNT

Here is a db<>fiddle where you can un-comment one of the two and see how it’s working.


Update:

i checked it again. it did not insert any row in the table. but it should insert the first one

Then you need to save the tran as

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement