If we don’t specify Begin Trans, Commit Trans, etc… and just use a simple SQL statement like this:
delete from myTable where id = 1
inside the stored procedure,
-
will SQL Server write the changes to the transaction log? If yes then how can we use them while there is no
Begin Transkeyword specified (we can’t use RollBack). -
When we write stored procedures is it a good practice to always use the transaction keywords or is it better to use them when they seem to be appropriate (for example when we need to rollback a change)?
edit: thank u guys. but how about the second part of my question 1?? how do i recover my data by using the transaction log??
By default SQL Server operates in
auto commitmode meaning each statement is automatically in its own transaction and gets committed automatically and written to the transaction log (or rolled back automatically in case of error). Once a transaction is committed it cannot be rolled back and you would need to roll forward from the last backup to rectify any mistakes (subject to a last backup being available and recovery model).You can alter this behaviour by using
set implicit_transactions onafter which nothing is committed until you issue acommitcommand.With regard to your question about stored procedures if you have multiple statements that you need treated atomically you would need explicit transaction control statements otherwise it is optional.