SQL server transaction - sql-server

I need to understand about sql server transaction? I have gone through some articles available on google but I have not understood anything. Can anyone help me?

You can explicitly start a transaction by writing BEGIN TRANSACTION. You end the transaction by running COMMIT TRANSACTION.
Before the COMMIT is run, the tables affected by your query can still be rolled back to the state they were in at the BEGIN TRANSACTION point-in-time.
This is useful when you are writing a stored procedure that is pumping a lot of data between tables. By dividing it in smaller parts using transactions, the whole bunch does not need to be "rolled back" when the procedure hangs, an error occurs or you cancel it manually.
An article that elaborates on this is for example this one.

See Understanding Transactions.

Database Journal have a lot of good articles abaut mentoed subject

Related

Where to put BEGIN TRAN, in the code or in the stored procedure?

Let's say I have a stored procedure that is doing 3 inserts. To make sure everything is working fine, I add a begin and commit tran in the stored procedure.
Then from the code side (.NET, C#), the programmer is also creating a transaction.
What will be the best approach for that?
Having in both places?
Having that in the C# code only?
Having that in the stored procedure only?
It's better to only do it in the stored procedure for a number of reasons:
The procedure can keep better control of when to begin and commit the transaction.
It can also control the isolation level, which should usually be set before the transaction starts.
It keeps database code close to the database (somewhat subjective).
If the connection is severed and the server does not realize, a transaction opened by the client may not be committed or rolled back for some time, and could leave locks hanging, causing a huge chain of blocking
The client starting and committing the transaction requires two extra round-trips over the network, which in a low-latency app may be problematic. (SET NOCOUNT ON should be used for the same reason.) The transaction and associated locking is also extended for that time, casuing further blocking problems.
Do use SET XACT_ABORT ON, in case of exceptions this will cause an automatic rollback and prevent them from leaving hanging transactions.
It may still may sense to use client-side transactions, especially with distributed transactions.
Having transactions in both client code and the procedure is silly and wasteful. Choose one or the other option and stick to it.

Purpose of TRAN and COMMIT in single/multiple SQL INSERT SELECT UPDATE DELETE statement

Can someone please explain to me in simple layman words what the SQL transaction is doing here?
Here is the scenario:
I am not SQL developer or data engineer. I wish to update column value depending on a filter that you see in where clause. I ran the query in database as I do have an admin rights, it was with approvals of course.
I typed in below command as per my need.
update idx_task set IDXTaskStatusDE=4 where ID='task_ID'
The developer then sent to me the following query and said I was doing the wrong way.
Use Works
begin tran
update idx_task set IDXTaskStatusDE=4 where ID='task_ID'
commit tran
Developer's email response:
When issuing adhoc statements directly against SQL, it is a good idea to wrap your statements in a transaction, just in case something goes wrong and you need to rollback. Updating the same table twice would be different than with or without the transaction. Hence, this is a professional practice which can be unknown to amateurs like you. This job seems to be outside your primary role. Please discuss with your boss and get your team a profession SQL developer.
My Efforts:
Hence, I am here after reading technical jargon to get in few words or with example how both queries would act differently anyway.
My Question:
1.) Can someone please provide a simple theoretical explanations of difference here, of significance of wrapping the single update statement in tran?
2.) is it for any prior, future, safety or professional practices in SQL developers community?
Thank you note to all saviours here
Thanks in advance to all types of responses. Your any type of feedback shall help me gain knowledge anyways :)
Take Care !!
Refer this question's thread. It will clear your confusion.
Using transaction on a single update statement
#Panagiotis Kanavos has pointed out and articulated perfectly.
Just know the simple meaning of following term while you read in regards to SQL Transactions:
1.) Atomic: "Atomic" means "cannot be divided or split in smaller parts". Applied to 1NF this means that a column should not contain more than one value. It should not compose or combine values that have a meaning of their own.
2.) Commit: A COMMIT statement in SQL ends a transaction within a relational database management system (RDBMS) and makes all changes visible to other users.
3.) Lock: Is a mechanism to ensure data consistency. SQL Server locks objects when the transaction starts. When the transaction is completed, SQL Server releases the locked object. Hence, in your case as pointed out by #Panagiotis Kanavos, the TRAN is doing the work of blocking all other commands if executed by other developers working in parallel to the same data that you are executing your UPDATE statement on.
Hope this helps. I do not think there would be more going down as "simple words" than this. Still feel free to ask if you still have a confusion.

Savepoint in database

I am researching on transaction savepoint in databases but what I am not getting is what exactly is the information which is saved during savepoint. It has to be little bulky since it will be used to rollback the transaction to the savepoint and restart from there. please provide some link or info to get detailed understanding. Thanks!
What you need is a regular backups...
Make sure that you can restore what you need - specific database, table etc.

is it possible to commit/rollback another procedures transaction in current procedure

i have two questions
1.i have two stored procedures. is it possible to commit/rollback another procedure's transaction in my current procedure.
2.i have two webservices two services connected with same database or linked server database. one webservices gotsucceed it transactions. when moving to the second webservice some error got occured. if error occured i have to rollback the previous webservice transactions.? is it possible. if anyone explain related to banking transactions like ATM
is it possible?
how?
explain related to banking sector with little understandable coding.
No, a commit must be issued from the same connection that the begin transaction statement was issued.
In this case you would first need to append the data tables with a "transaction" field or something similar that will uniquely identify each transaction. If the second webservice needed to issue a rollback that touched the work of the first webservice, it would have to call a custom process would then issue deletes looking for the transaction identifier that you have built into the tables. There's no built-in functionality of the db engine to accommodate this out of the box.

What happens to connections when taking SQl Server Database Offline?

I have recently tried a big merge of 2 databases. We recreated the schema from Database 2 into Database 1 and created a script to transfer all data from database 2 into Database 1. This script takes about 35 min to run and have transaction handling with:
BEGIN TRANSACTION
...
IF(##error<>0)
COMMIT TRANSACTION
ELSE
ROLLBACK TRANSACTION
The full script is a bit sensitive but here is some SQL that have the same structure: http://pastebin.com/GWJ3ZnkF
We ran the script and all data was transfered without errors. We tested the systems running with the new combined database (removed access rights to the old database).
But as a last task we wanted to take the old database offline to make sure no one used that database. To do this we used:
ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE
This was bad. After this line of SQL code all data in the combined database that we just copied was suddenly gone. I first asumed it wasn't really finished so the "Rollback immediate" sounds like it have performed a rollback on my transaction..
But why? Wasn't the transaction allready committed?
Also I tried running the same script again a few times but after every attempt no data was copied even if it said the script was successfull. I have no idea why... did it remember my offline rollback somehow?
What is really happening to my connections?
Sounds like you had a pending transaction uncommitted and you forced it to rollback, loosing some of the work. The rest is explained by how your scripts are structured. Is unlikely your script had a single transaction from start to bottom. Only the last transaction was rolled back, so the database was left now in a state in which it is 'half copied'. Probably your script does various checks and this intermediate state sends the script on the 'ELSE' branches where it does not do the proper work (ie. apparently does nothing).
W/o posting the exact script, is all speculation anyway.
Right now you need to restore the database to a consistent state, the one before your data copy. Use the backup you took before the data move (you did take a backup, right?). for extra credit, make sure your script is idempotent and works correctly on a half-updated database.
I'd double-check to make sure that there are no outstanding transactions. Either go through the file and count the number of BEGIN TRANSACTION vs COMMIT TRANSACTION lines, or add a statement to the end of it to SELECT ##TRANCOUNT to ensure that there are no open transactions remaining.
If your data has been committed, there should be no way it can be lost by disconnecting you.
WITH ROLLBACK IMMEDIATE:
All incomplete transactions will be rolled back and any other
connections to the database will be
immediately disconnected.
Sounds like someone got the 2 databases mixed up or maybe there is an outstanding transaction?.... Can you post your entire script?
Ref: ALTER DATABASE.
Rather than only checking ##ERROR, inspect ##TRANCOUNT as well.

Resources