|
-
May 26th, 2005, 06:47 AM
#1
Thread Starter
Junior Member
Return ID after update statement
Is there a function in VB.NET or C# that returns me the ID of a record when i do an insertstatement?
something like:
dim id = cmd.ExecuteNonQuery(QUERY,connection)
-
May 26th, 2005, 07:22 AM
#2
Re: Return ID after update statement
@@IDENTITY is a global variable of most (all?) SQL compliant databases. Use "SELECT @@IDENTITY" to get the last ID value generated. This is independant of the development language.
-
May 26th, 2005, 07:42 AM
#3
Frenzied Member
Re: Return ID after update statement
In other words, in your QUERY, have a second statement preceded by a semicolon (SELECT @@IDENTITY) or u can use a stored procedure with the last line (RETURN @@IDENTITY).
ie:
VB Code:
"INSERT INTO table (column) VALUES (value);SELECT @@IDENTITY"
-
May 26th, 2005, 07:46 AM
#4
Hyperactive Member
Re: Return ID after update statement
Note that if you are using Access you will have to perform the Select @@Identity in a seperate query.
ie (Pesudocode!)
cmdInsert.execute
autonumber = cmdGetID.execute
-
May 26th, 2005, 07:46 AM
#5
Frenzied Member
Re: Return ID after update statement
another thought just occured to me...If you have triggers that may get fired off when you insert, you will get back the identity of the other tables, etc...an alternative is to use Scope Identity.
It is like @@Identity, but it guarantees that if there are triggers firing on the insert you will get the identity of the record YOU inserted. If there are triggers firing @@Identity will return the identity of the last record inserted by the trigger program. Scope Identity is new in SQL Server 2000.
FROM A BOOK ONLINE:
SCOPE_IDENTITY Returns the last IDENTITY value inserted into an IDENTITY column in the same scope. A scope is a module -- a stored procedure, trigger, function, or batch. Thus, two statements are in the same scope if they are in the same stored procedure, function, or batch.
Syntax
SCOPE_IDENTITY( )
-
May 26th, 2005, 08:32 AM
#6
Fanatic Member
Re: Return ID after update statement
Another solution to the identity issue is using a key table. The key table has two columns - TableName and NextValue - and exists solely to provide PKs. Setting up a class to access the key table means you can also grab an array of PKs in one swoop. Another benefit of the key table is that if you're writing test code (say w/ NUnit) you can reset the key table values at the end of the test code.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|