I have 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.
If you insert records into a table which contains auto-incremented column, using a Statement or, PreparedStatement objects. You can retrieve the values of that particular column, generated by them object using the getGeneratedKeys() method.
Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.
The whole idea of a primary key is to have a unique identifier for each row, so you can not do that. However, if you want a way of grouping rows, you can either add a group column to your table, or create a table for the grouping. For example group_members and have that contain two columns, "group_id" and "row_id".
For MS SQL Server:
SCOPE_IDENTITY()
will return you the last generated identity value within your current scope:
SELECT SCOPE_IDENTITY() AS NewID
For SQL Server 2005 and up, and regardless of what type your primary key is, you could always use the OUTPUT
clause to return the values inserted:
INSERT INTO dbo.YourTable(col1, col2, ...., colN) OUTPUT Inserted.PrimaryKey VALUES(val1, val2, ....., valN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With