473,382 Members | 1,329 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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 9729
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=localhost;Integrated Security=SSPI;Initial Catalog=northwind")

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

catDA.InsertCommand = New SqlCommand("InsertCategory", nwindConn)
catDA.InsertCommand.CommandType = CommandType.StoredProcedure

catDA.InsertCommand.Parameters.Add("@CategoryName" , SqlDbType.NChar, 15,
"CategoryName")

Dim myParm As SqlParameter = catDA.InsertCommand.Parameters.Add("@Identity",
SqlDbType.Int, 0, "CategoryID")
myParm.Direction = ParameterDirection.Output

nwindConn.Open()

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

Dim newRow As DataRow = catDS.Tables("Categories").NewRow()
newRow("CategoryName") = "New Category"
catDS.Tables("Categories").Rows.Add(newRow)

catDA.Update(catDS, "Categories")

nwindConn.Close()
"Justin" <Ju****@discussions.microsoft.com> wrote in message
news:C4**********************************@microsof t.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=localhost;Integrated Security=SSPI;Initial Catalog=northwind")

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

catDA.InsertCommand = New SqlCommand("InsertCategory", nwindConn)
catDA.InsertCommand.CommandType = CommandType.StoredProcedure

catDA.InsertCommand.Parameters.Add("@CategoryName" , SqlDbType.NChar, 15,
"CategoryName")

Dim myParm As SqlParameter = catDA.InsertCommand.Parameters.Add("@Identity",
SqlDbType.Int, 0, "CategoryID")
myParm.Direction = ParameterDirection.Output

nwindConn.Open()

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

Dim newRow As DataRow = catDS.Tables("Categories").NewRow()
newRow("CategoryName") = "New Category"
catDS.Tables("Categories").Rows.Add(newRow)

catDA.Update(catDS, "Categories")

nwindConn.Close()
"Justin" <Ju****@discussions.microsoft.com> wrote in message
news:C4**********************************@microsof t.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_Identity.

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.RowUpdated, AddressOf da_Handle_RowUpdated

'parent table
da_Hdr.Update(NewHdrRecords)

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

Private Sub da_Handle_RowUpdated(ByVal sender As Object, ByVal e As
SqlRowUpdatedEventArgs)
If e.Status = UpdateStatus.Continue And e.StatementType
=StatementType.Insert Then
e.Row("key") = GetIdentity(e.Command.Connection)
e.Row.AcceptChanges()

'use this if you do not want to AcceptChanges for each row.
'e.Status = UpdateStatus.SkipCurrentRow
End If
End Sub
================================================== ==============
Private Function GetIdentity(ByRef cnn As SqlConnection) As Integer
Dim oCmd As New SqlCommand("SELECT @@IDENTITY", cnn)
Dim x As Object = oCmd.ExecuteScalar()
Return CInt(x)
End Function
================================================== ==============

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

Private Sub da_Handle_OracleRowUpdated(ByVal sender As Object, ByVal e As
OracleRowUpdatedEventArgs)
If e.Status = UpdateStatus.Continue And e.StatementType
=StatementType.Insert Then
e.Row("key") = GetOracleSequence(e.Command.Connection)
e.Row.AcceptChanges()

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

Private Function GetOracleSequence(ByRef cnn As OracleConnection) As
Integer
Dim oCmd As New OracleCommand("SELECT SEQ_EIMHDR_EIMKEY.CURRVAL FROM
DUAL", cnn)
Dim x As Object = oCmd.ExecuteScalar()
Return CInt(x)
End Function
================================================== ==============

--
Joe Fallon


"Justin" <Ju****@discussions.microsoft.com> wrote in message
news:C4**********************************@microsof t.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
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...
2
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...
2
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
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...
9
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...
8
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...
1
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...
4
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...
15
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.