473,757 Members | 7,200 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting The new Identity Value

I have a VB.NET app in which I am using the following code to add a new row.
ds.Tables("Unit sTable").Rows.A dd(dr) ' Add the new row

da.InsertComman d = cmdBuilder.GetI nsertCommand

da.Update(ds, "UnitsTable ")

At this point I want to get the value of the Identity field that has just
been added to the underlying table ("UnitsTable " is based on a Select
against a table named "Units")
I searched google but the examples I found were using recordsets and I could
not adapt them to work. Pointers to any examples or explinations will be
appreciated.

Wayne
Nov 21 '05 #1
2 2539
For SQL Server, there is a way to send 2 statements separated by a
semi-colon.

The first is your update statement the second is:
Select @@Scope_Identit y

So you should be able to set your ID to the returned Identity value if you
send 2 statements.

=============== =============== =============== =========
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_Eimhdr.RowUp dated, AddressOf da_Handle_RowUp dated

'parent table
da_Eimhdr.Updat e(NewEimhdrReco rds)

'child table
da_Eimln.Update (NewEimlnRecord s)
=============== =============== =============== =============== ====
'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.I nsert Then
e.Row("eimkey") = 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
=============== =============== =============== =============== ====
--
Joe Fallon


"Wayne Wengert" <wa************ ***@wengert.com > wrote in message
news:On******** ******@TK2MSFTN GP11.phx.gbl...
I have a VB.NET app in which I am using the following code to add a new row. ds.Tables("Unit sTable").Rows.A dd(dr) ' Add the new row

da.InsertComman d = cmdBuilder.GetI nsertCommand

da.Update(ds, "UnitsTable ")

At this point I want to get the value of the Identity field that has just
been added to the underlying table ("UnitsTable " is based on a Select
against a table named "Units")
I searched google but the examples I found were using recordsets and I could not adapt them to work. Pointers to any examples or explinations will be
appreciated.

Wayne

Nov 21 '05 #2
Joe;

Thanks for all that information. I used your function approach and that
works fine. I am trying to understand the handler approach and will also try
that to see what I learn.

Wayne

"Joe Fallon" <jf******@nospa mtwcny.rr.com> wrote in message
news:%2******** *******@TK2MSFT NGP09.phx.gbl.. .
For SQL Server, there is a way to send 2 statements separated by a
semi-colon.

The first is your update statement the second is:
Select @@Scope_Identit y

So you should be able to set your ID to the returned Identity value if you
send 2 statements.

=============== =============== =============== =========
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_Eimhdr.RowUp dated, AddressOf da_Handle_RowUp dated

'parent table
da_Eimhdr.Updat e(NewEimhdrReco rds)

'child table
da_Eimln.Update (NewEimlnRecord s)
=============== =============== =============== =============== ====
'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.I nsert Then
e.Row("eimkey") = 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
=============== =============== =============== =============== ====
--
Joe Fallon


"Wayne Wengert" <wa************ ***@wengert.com > wrote in message
news:On******** ******@TK2MSFTN GP11.phx.gbl...
I have a VB.NET app in which I am using the following code to add a new

row.
ds.Tables("Unit sTable").Rows.A dd(dr) ' Add the new row

da.InsertComman d = cmdBuilder.GetI nsertCommand

da.Update(ds, "UnitsTable ")

At this point I want to get the value of the Identity field that has just been added to the underlying table ("UnitsTable " is based on a Select
against a table named "Units")
I searched google but the examples I found were using recordsets and I

could
not adapt them to work. Pointers to any examples or explinations will be
appreciated.

Wayne


Nov 21 '05 #3

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

Similar topics

2
2631
by: Benny | last post by:
Dear All, Suppose in the program a record is added to a table whose primary key is a identity field. If I really want to get the lastest value for that field after the insertion, is it the best way to use IDENT_CURRENT() to obtain this value? Thanks for your kind attention Yours faithfully,
2
4666
by: Edward | last post by:
SQL 7.0 I have a form in ASP.NET and I want to write the values to the SQL Server tables. The tables are Customer and Address tables. There will be an insert into the Customer table, and I need to use the Identity of this inserted record for the Foreign Key in the Address table insert.
5
4011
by: Eugene | last post by:
I have a table EugeneTest(id_num, fname, minit, lname) where field "id_num" is type IDENTITY and has UNIQUE constraint Let's say 2 user execute this code at the same time: DECLARE @return integer use EugeneTest INSERT employees ( fname, minit, lname) VALUES
4
2136
by: Nathan Sokalski | last post by:
I am using ASP.NET to insert records into a Microsoft Access Database. My primary keys are of type Autonumber. However, because some of the tables have relationships I need to know the value of the Autonumber field when I use the Insert command so that I can put it in the foreign key field of other tables. I am using VB.NET to code my ASP.NET application. How can I do this? Thanks. -- Nathan Sokalski njsokalski@hotmail.com...
3
6999
by: Jason L James | last post by:
Hi all, I recently wrote a vb.net app using oledb to an access database. When I inserted new rows in my datatable the identity column was automatically created. This app used an un-typed dataset. My current app is using sqlClient and a typed dataset that I created by exporting an xsd
41
3160
by: pb648174 | last post by:
In a multi-user environment, I would like to get a list of Ids generated, similar to: declare @LastId int select @LastId = Max(Id) From TableMania INSERT INTO TableMania (ColumnA, ColumnB) SELECT ColumnA, ColumnB From OtherTable Where ColumnC > 15 --get entries just added
1
20988
by: Brad Eck | last post by:
In Access, newID returns a unique for the table. In SQL Server, newid() returns a GUID - unique in the world. I do not need or desire that complexity. Is there a way to get a simple unique int on the table in SQL Server? Brad Eck http://www.sitesdynamic.com http://www.basketsetcetera.com *** Sent via Developersdex http://www.developersdex.com ***
3
3874
by: Atul | last post by:
Hi, I am running .NET Framework 2.0 on windows XP SP2. I am stuck in a situation where I need to find out a list of all active sessions running in IIS for a web application. I know that .NET 2.0 has introduced a new class that facilitate this task very easily, somehow couldnt recall its name. Any help would be highly appreciated.
33
11864
by: JamesB | last post by:
I am writing a service that monitors when a particular app is started. Works, but I need to get the user who is currently logged in, and of course Environment.UserName returns the service logon (NT_AUTHORITY\SYSTEM). I understand that when the service starts, no user may be logged in, but that's ok, as the app I am monitoring can only be run by a logged in user. Do I need to use WMI to get the user context of Explorer.exe or is there a...
0
9489
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
9298
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
10072
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...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
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...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
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.