473,656 Members | 2,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving Identity After Dataset update

I have created a dataset with two tables and an insert command, I need to be
able to retreive the Key Identity after inserting into table "A" for use in
table "B".

Should I use ExecuteScalar() or is there a better solution?

Thanks, Justin.
Nov 18 '05 #1
3 9749
Hi Justin,

I think you want to use ADO.NET's InsertCommand for this.

You might want to check this:

http://msdn.microsoft.com/library/de...anidcrisis.asp

Retrieving Identity or Autonumber Values

http://msdn.microsoft.com/library/de...mberValues.asp
"The following code example shows how to return the auto-incremented value
as the output parameter and specify it as the source value for the
CategoryID column in the DataSet.

[Visual Basic]
Dim nwindConn As SqlConnection = New SqlConnection(" Data
Source=localhos t;Integrated Security=SSPI;I nitial Catalog=northwi nd")

Dim catDA As SqlDataAdapter = New SqlDataAdapter( "SELECT CategoryID,
CategoryName FROM Categories", nwindConn)

catDA.InsertCom mand = New SqlCommand("Ins ertCategory", nwindConn)
catDA.InsertCom mand.CommandTyp e = CommandType.Sto redProcedure

catDA.InsertCom mand.Parameters .Add("@Category Name", SqlDbType.NChar , 15,
"CategoryNa me")

Dim myParm As SqlParameter = catDA.InsertCom mand.Parameters .Add("@Identity ",
SqlDbType.Int, 0, "CategoryID ")
myParm.Directio n = ParameterDirect ion.Output

nwindConn.Open( )

Dim catDS As DataSet = New DataSet
catDA.Fill(catD S, "Categories ")

Dim newRow As DataRow = catDS.Tables("C ategories").New Row()
newRow("Categor yName") = "New Category"
catDS.Tables("C ategories").Row s.Add(newRow)

catDA.Update(ca tDS, "Categories ")

nwindConn.Close ()
"Justin" <Ju****@discuss ions.microsoft. com> wrote in message
news:C4******** *************** ***********@mic rosoft.com...
I have created a dataset with two tables and an insert command, I need to
be
able to retreive the Key Identity after inserting into table "A" for use
in
table "B".

Should I use ExecuteScalar() or is there a better solution?

Thanks, Justin.


Nov 18 '05 #2
I have tried that code, what I can't figure out is exactly what variable
holds the identity. If its "myParam" then how do I cast it to an int variable?

Thanks, Justin.

"Ken Cox [Microsoft MVP]" wrote:
Hi Justin,

I think you want to use ADO.NET's InsertCommand for this.

You might want to check this:

http://msdn.microsoft.com/library/de...anidcrisis.asp

Retrieving Identity or Autonumber Values

http://msdn.microsoft.com/library/de...mberValues.asp
"The following code example shows how to return the auto-incremented value
as the output parameter and specify it as the source value for the
CategoryID column in the DataSet.

[Visual Basic]
Dim nwindConn As SqlConnection = New SqlConnection(" Data
Source=localhos t;Integrated Security=SSPI;I nitial Catalog=northwi nd")

Dim catDA As SqlDataAdapter = New SqlDataAdapter( "SELECT CategoryID,
CategoryName FROM Categories", nwindConn)

catDA.InsertCom mand = New SqlCommand("Ins ertCategory", nwindConn)
catDA.InsertCom mand.CommandTyp e = CommandType.Sto redProcedure

catDA.InsertCom mand.Parameters .Add("@Category Name", SqlDbType.NChar , 15,
"CategoryNa me")

Dim myParm As SqlParameter = catDA.InsertCom mand.Parameters .Add("@Identity ",
SqlDbType.Int, 0, "CategoryID ")
myParm.Directio n = ParameterDirect ion.Output

nwindConn.Open( )

Dim catDS As DataSet = New DataSet
catDA.Fill(catD S, "Categories ")

Dim newRow As DataRow = catDS.Tables("C ategories").New Row()
newRow("Categor yName") = "New Category"
catDS.Tables("C ategories").Row s.Add(newRow)

catDA.Update(ca tDS, "Categories ")

nwindConn.Close ()
"Justin" <Ju****@discuss ions.microsoft. com> wrote in message
news:C4******** *************** ***********@mic rosoft.com...
I have created a dataset with two tables and an insert command, I need to
be
able to retreive the Key Identity after inserting into table "A" for use
in
table "B".

Should I use ExecuteScalar() or is there a better solution?

Thanks, Justin.


Nov 18 '05 #3
The solution is to set up cascade update in your dataset so that when the
new Identity value is returned from the database you update the master table
and cascade the change to the child.
You have to trap the RowUpdated event and then post the new identity value.

For SQL Server, there is a way to send 2 statements separated by a
semi-colon.
The first is your Parent update statement the second is Select
@@Scope_Identit y.

For Access and Oracle (and SQL Server if you don't use multiple statements):
You have to trap the RowUpdated event and then post the new identity value.

=============== =============== =============== =============== ====
In my update method I have some code like this:

'handle the RowUpdated event to get the Identity value back from
SQL Server
'w/o the real Identity value, the child records won't be added to
SQL Server.
AddHandler da_Hdr.RowUpdat ed, AddressOf da_Handle_RowUp dated

'parent table
da_Hdr.Update(N ewHdrRecords)

'child table
da_Ln.Update(Ne wLnRecords)
=============== =============== =============== =============== ====
'this is how to handle the insert of each row:

Private Sub da_Handle_RowUp dated(ByVal sender As Object, ByVal e As
SqlRowUpdatedEv entArgs)
If e.Status = UpdateStatus.Co ntinue And e.StatementType
=StatementType. Insert Then
e.Row("key") = GetIdentity(e.C ommand.Connecti on)
e.Row.AcceptCha nges()

'use this if you do not want to AcceptChanges for each row.
'e.Status = UpdateStatus.Sk ipCurrentRow
End If
End Sub
=============== =============== =============== =============== ====
Private Function GetIdentity(ByR ef cnn As SqlConnection) As Integer
Dim oCmd As New SqlCommand("SEL ECT @@IDENTITY", cnn)
Dim x As Object = oCmd.ExecuteSca lar()
Return CInt(x)
End Function
=============== =============== =============== =============== ====

For Oracle - I use this code:
=============== =============== =============== =============== ====

Private Sub da_Handle_Oracl eRowUpdated(ByV al sender As Object, ByVal e As
OracleRowUpdate dEventArgs)
If e.Status = UpdateStatus.Co ntinue And e.StatementType
=StatementType. Insert Then
e.Row("key") = GetOracleSequen ce(e.Command.Co nnection)
e.Row.AcceptCha nges()

'use this if you do not want to AcceptChanges for each row.
'e.Status = UpdateStatus.Sk ipCurrentRow
End If
End Sub

Private Function GetOracleSequen ce(ByRef cnn As OracleConnectio n) As
Integer
Dim oCmd As New OracleCommand(" SELECT SEQ_EIMHDR_EIMK EY.CURRVAL FROM
DUAL", cnn)
Dim x As Object = oCmd.ExecuteSca lar()
Return CInt(x)
End Function
=============== =============== =============== =============== ====

--
Joe Fallon


"Justin" <Ju****@discuss ions.microsoft. com> wrote in message
news:C4******** *************** ***********@mic rosoft.com...
I have created a dataset with two tables and an insert command, I need to
be
able to retreive the Key Identity after inserting into table "A" for use
in
table "B".

Should I use ExecuteScalar() or is there a better solution?

Thanks, Justin.

Nov 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2023
by: Taras | last post by:
Hello! I have a problem. I'm using a dataset in VB.NET with multiple tables with relations between them. I would like dataset to update to all related tables with right identity, when certain record is added. The problem is that I don't know how to do it, when I'm not using stored procedures. I found an article in which OnRowUpdated event of the dataadapter is used. On this event ExecuteScalar method of the oledbcommand object is called...
2
5263
by: Niyazi | last post by:
Hi, I have not understand the problem. Before all the coding with few application everything worked perfectly. Now I am developing Cheque Writing application and when the cheque is clear the user have to open a form and entera date so we know in report that the desiered check has been cleared. It takes me while to wrtie. But when I try to update the datagrid changes via dataset to MS Access 2003 I get an error that simply says...
2
12663
by: Mojtaba Faridzad | last post by:
Hi, Please check these lines: DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet, "mytable"); DataRow row; row = dataSet.Tables.Rows; row.BeginEdit(); row = "555";
1
2769
by: Taras | last post by:
Hello! I have a problem. I'm using a dataset in VB.NET with multiple tables with relations between them. I would like dataset to update to all related tables with right identity, when certain record is added. The problem is that I don't know how to do it, when I'm not using stored procedures. I found an article in which OnRowUpdated event of the dataadapter is used. On this event ExecuteScalar method of the oledbcommand object is called...
9
1543
by: Kevin Hodgson | last post by:
I'm experiencing a strange Dataset Update problem with my application. I have a dataset which has a table holding a set of customer information records. (address, contact, info, etc.) I have a series of ComboBoxes (Client Number for selection), and text fields to show the other data bound to this Dataset.table If I change a value for the first client in the list, and press my update client button, the data is successfully updated to the...
8
9253
by: Dave | last post by:
I have a form with a label that should show an invoice number. The invoice number should be generated by sql Server using an autoincremented technique. However, after reading several articles, it seems that I can only retrieve this value after an INSERT has been done in the database. I want to find out what this autoincremented before an insertion.-- L. A. Jones
1
1482
by: Krish2007 | last post by:
Hi, Consider the following scenario I have a Database source i had filled in my dataset with the help of Dataadapter after working on the dataset i want the data source to be updated back with the new data available with me. It may be a small change in the employee_name column for example. And if the data had already been modified even deleted by some other user of the database then my dataset update method will prone to some error.
4
15007
by: Mark Olbert | last post by:
I am struggling with trying to retrieve the value of an autoincrement identity field after a DetailsView Insert operation. The DetailsView is bound to an SqlDataSource control. So far as I can tell, nowhere in the arguments for either the Inserted event for the DetailsView or the Inserted event for the SqlDataSource control is the value stored. Adding a dummy bound column for the identity field to the DetailsView doesn't work, either. ...
15
3523
by: gunnar.sigurjonsson | last post by:
I´m having some problem retrieving identity value from my newly inserted row into a view. I have two tables T1 and T2 which I define as following CREATE TABLE T1 ( id BIGINT GENERATED ALWAYS AS IDENTITY ( START WITH 1
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5629
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.