Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net sql last inserted ID

i'm using VB.NET with an Access Database, I insert values but then I need to get the last inserted ID (auto number) and insert that into a related table.

I have tried @@IDENTITY and MAX(column) but @@IDENTITY returns zero and MAX isn't very dependable (sometimes slow to insert data, so get the ID before the inserted one).

Dim insertSql = datalayer.getDataTable((String.Format("INSERT INTO users (username) VALUES ({0})", username)))

Dim newID = datalayer.getDataTable((String.Format("SELECT @@IDENTITY FROM users")))


Dim con As OleDbConnection = getConnection()
con.Open()
Dim sqlCommand As OleDbCommand = New OleDbCommand(String.Format(insertSql), con)
sqlCommand.ExecuteNonQuery()

This is done in two functions so the above code might look confusing, but thats just taken from the two functions. The two statements are executed, but I have just shown one being executed as an example.

Is there and alternative to @@IDENTITY and MAX, as I carn't seem to see how am going wrong with @@IDENTITY?

Thanks for any advice :).

like image 402
Elliott Avatar asked Dec 13 '10 01:12

Elliott


People also ask

How do I get the last inserted ID in SQL query?

IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.

How do I get the last inserted row ID?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.

What is last insert ID?

Definition and Usage. The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I find the last ID of a database?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.


1 Answers

Its is absolutely crucial than SELECT @@IDENTITY is executed on the same connection (and transaction) than the insert. If your getDataTable() method creates a new connection for each call, then that is why its not working.

Update

Another approach which is preferable is to execute the two statements in one

sql = "INSERT INTO...;SELECT @@IDENTITY..." 
Dim id = sqlCommand.ExecuteScalar(sql)

Update again

It seems like you can't execute multiple functions like this against a MS Access database, Running multiple SQL statements in the one operation.

like image 146
Pauli Østerø Avatar answered Oct 05 '22 18:10

Pauli Østerø