I have a little witty problem. Say, I inserted a row with some data in a table where a primary key is present. How would one "SELECT" the primary key of the row one just inserted?
I should have been more specific and mentioned that I'm currently using SQLite.
For MS SQL Server:
SCOPE_IDENTITY()
will return you the last generated identity value within your current scope:That, in theory, should return you that last inserted id. If it's a busy database with many inserts going on it may not get the one you just did but another.
Anyhow, an alternative to other methods.
For Postgresql:
Source: https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id
If you need to retrieve the new index in MS SQL when there are triggers on the table then you have to use a little workaround. A simple OUTPUT will not work. You have to do something like this (in VB.NET):
If using .NET, then the return value from this query can be directly cast to an integer (you have to call "ExecuteScalar" on the .NET SqlCommand to get the return).
For MySQL, use LAST_INSERT_ID()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
You should also be able to start a transaction, insert the row, and select the row using some field that has a unique value that you just inserted, like a timestamp or guid. This should work in pretty much any RDBMS that supports transactions, as long as you have a good unique field to select the row with.
MS SQL
You can use @@IDENTITY. After an insert statement, you can run:
This will give you the primary key of the record you just inserted. If you are planning to use it later, I suggest saving it:
If you are using this in a stored procedure and want to access it back in your application, make sure to have nocount off.