How to get the Id from the last inserted record?
If you want to know what the id is from the last inserted record, you can do a number of things.
In the following methods I suppose you have a table Test, with just two fields: id as identity field and name as text.
Using scope_identity()
You can put everything in one Sql. By combining the insert-Sql with the select scope_identity() you can easily retrieve the id last used in any Insert-command:
insert into test values('testname');select scope_identity();
In Visual Basic.Net you can do the following:
Dim cmd As New OdbcCommand("insert into test values('test2');select scope_identity()", MyOdbcConnection) Dim i As Long = cmd.ExecuteScalar
Be aware this function returns the last id, not caring baout the table you are interested in. Probably you want to use the following:
Using Ident_Current('Tablename')
A better possibility I mention here is Ident_Current('Tablename'). This method retrieves the last inserted id for a specific table:
insert into test values('test2');select IDENT_CURRENT('test')
In Visual Basic.Net you can do like this:
Dim cmd As New OdbcCommand("insert into test values('test2');select IDENT_CURRENT('test')", MyOdbcConnection) Dim i As Long = cmd.ExecuteScalar
Using Max()
After inserting the record, you can get also the maximum id with the max() function:
insert into test values('testname');select max(id) from test;
In Visual Basic.Net you can do like this:
Dim cmd As New OdbcCommand("insert into test values('testname');select max(id) from test;", MyOdbcConnection) Dim i As Long = cmd.ExecuteScalar
|