Solved

Using BeginTran/Commit Tran for MS SQL in c#

Posted on 2004-08-12
9
961 Views
Last Modified: 2010-08-05
Hi All,

I need to know how to use the BeginTran and Commit Tran in C#.

Here's the basic background on the problem:
I have a webpage where the user can add new record.  The record is inserted into a MS SQL DB.  the table has a primary key.

What I need is to get the ID (primary key) of the record that was inserted.  

I can get the last record that was added using the select Ident_current.  So if I tie the Insert Into and the select ident_current into one transaction, I can get an accurate ID of the record.

So, how do I do this in .Net using C#?????

Please be kind and elobrate your comments
Thanks.
0
Comment
Question by:xile001
  • 3
  • 2
  • 2
  • +1
9 Comments
 
LVL 20

Expert Comment

by:ihenry
ID: 11785798
Except select statement how many insert/update statements do you have?
0
 
LVL 8

Assisted Solution

by:boulder_bum
boulder_bum earned 250 total points
ID: 11785814
You'd get the value returned from the final SELECT of your SQL/Sproc by using SqlCommand.ExecuteScalar() which returns a single value. The INSERT will still execute, you'll just get a value back in addition.
0
 
LVL 20

Expert Comment

by:ihenry
ID: 11785849
Just want to mention, if you have just a single insert/update statement you don't need transaction to handle that.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 17

Expert Comment

by:AerosSaga
ID: 11785964
If you want it in VB let me know.

Regards,

Aeros
0
 

Author Comment

by:xile001
ID: 11788182
boulder_bum:
That's interesting.  I didn't know that method return the value.  That would works perfectly without me having to use the transaction.

though, I did find the information for using transaction in c#.  So incase anyone needs it, here's the link:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconperformingtransactionusingadonet.asp
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 11788252
"I didn't know that method return the value."

Yeah. The method simply returns the first value returned, so if you have a statement like:

INSERT INTO --etc etc
SELECT @@IDENTITY AS MyNewIdentity

then ExecuteScalar will snag the value of "MyNewIdentity".
0
 

Author Comment

by:xile001
ID: 11788330
buolder_bum:

If I use the Insert into (val.....) values (x1,....), will it return the primary key of the inserted row using the execute scalar?

0
 
LVL 17

Accepted Solution

by:
AerosSaga earned 250 total points
ID: 11789120
Yes it can be done like so:

cmd.CommandText = "INSERT INTO ShippingAddresses (FirstName, LastName, Address1, Address2, City, State, Zip, Country)" & _
                    " Values ('" & CStr(Session("BillFirstName")) & "','" & _
            CStr(Session("BillLastName")) & "','" & CStr(Session("BillAddress1")) & "','" & CStr(Session("BillAddress2")) & "','" & _
            CStr(Session("BillCity")) & "','" & CStr(Session("BillState")) & "','" & CStr(Session("BillZip")) & "','" & _
            CStr(Session("BillCountry")) & "')"
            End If
            cmd.ExecuteNonQuery()
            cmd.CommandText = "SELECT LAST_INSERT_ID() AS ShippingAddressID"
            cmd.ExecuteScalar()
            strShippingAddressID = CStr(cmd.ExecuteScalar())
            Me.lblShippingAddressID.Text = strShippingAddressID
            cmd.CommandText = "INSERT INTO Orders (CustomerID, OrderID, Total, Shipping, Tax, OrderDate, AuthNetAuthCode, AuthNetTransID, CCType, ShipAddressID)" & _
            " Values ('" & Me.lblCustomerID.Text.ToString & "','" & Me.lblTrackingID.Text.ToString & "','" & Me.lblOrderSubTotal.Text.ToString & "','" & _
            Me.lblTotalTax.Text & "','" & Me.lblShippingTotal.Text & "','" & ThisDay & "','" & "" & "','" & "" & "','" & Me.ddlCreditType.SelectedValue & "','" & Me.lblShippingAddressID.Text & "')"
            'Insert Null AuthNet Codes to create OrderTrackingID, will update after transaction
            cmd.ExecuteNonQuery()
            cmd.CommandText = "SELECT LAST_INSERT_ID() As OrderTrackingID"
            cmd.ExecuteScalar()
            strOrderTrackingID = CStr(cmd.ExecuteScalar())
            Me.lblOrderTrackingID.Text = strOrderTrackingID

Regards,

Aeros
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 11789948
"will it return the primary key of the inserted row using the execute scalar"

It all depends on the SQL. The trick is not so much in ExecuteScalar (which simply selects a single value) as it is in the statement you use. After the INSERT, you want to have a little bit of SQL that returns the primary key like AerosSaga's "SELECT LAST_INSERT_ID()" or the identity selection I mentioned, "SELECT @@IDENTITY".
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question