Transactions
Let's say you have a managed stored procedure called SampleSP that has the following code:
C#
// as usual, connection strings shouldn't be
// hardcoded for production code
using(SqlConnection conn = new
SqlConnection("server=MyServer;
database=AdventureWorks;
user id=MyUser; password=MyPassword")) {
conn.Open();
// insert a hardcoded row for this sample
SqlCommand cmd = new SqlCommand
("INSERT INTO HumanResources.
Department " + "(Name, GroupName)
VALUES ('Databases', 'IT'); SELECT
SCOPE_IDENTITY()", conn);
outputId = (int)cmd.ExecuteScalar();
}
Visual Basic .NET
Dim cmd as SqlCommand
' as usual, connection strings shouldn't be
' hardcoded for production code
Using conn As New SqlConnection( _
"server=MyServer;
database=AdventureWorks;
user id=MyUser; password=MyPassword")
conn.Open()
' insert a hardcoded row for this sample
cmd = New SqlCommand("INSERT INTO
HumanResources.Department " _ &
"(Name, GroupName) VALUES
('Databases', 'IT'); SELECT SCOPE_
IDENTITY()", conn)
outputId = CType(cmd.ExecuteScalar(),
Integer)
End Using
What happens if you do this in T-SQL?
BEGIN TRAN
DECLARE @id INT
-- create a new department and get its ID
EXEC SampleSP @id OUTPUT
-- move employees from department 1 to the new department
UPDATE Employees SET DepartmentID = @id WHERE DepartmentID = @id
-- now undo the entire operation
ROLLBACK