International Developer Logo Last Updated 27.08.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Managed data access inside SQL Server with ADO.NET and SQLCLR


Pablo Castro   13.02.06


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




   Previous Page  ... 11 12 13 14 15 16 17 18 19 20 ... Next Page   

HAVE YOUR SAY
This article is rated  Rate this article