tags:

views:

100

answers:

2

I want to add a row using SQLs INSERT statement. Is it possible that as part of this statement I can somehow get the value of the column userId which I don't update but is the AUTO_INCREMENT primary key. I need this value to update another table, however I can't follow the Insert statement immediately with a SELECT statement as there is no other unique identifier in the table on which to select.

INSERT INTO objectUrl(disp_name, loggedIn) VALUES('please change this', true)

Is it possible to get the row number (column name userId) and if so how do you do it?

+2  A: 

For MySQL you have:

select last_insert_id()
LittleBobbyTables
+3  A: 

In MySQL it's called LAST_INSERT_ID(). I believe to be technically correct, the two statements should be wrapped in a transaction so that some other INSERT doesn't mess up what ID you get back.

In SQL Sever you have IDENT_CURRENT(‘tablename’) which will only grab it from that table (still need a transaction to be safe). You could also use SCOPE_IDENTITY() which theoretically will always return the one you expect as long as you aren't doing something weird with your connection.

colithium
What could be 'weird' about a connection to prevent `SCOPE_IDENTITY` from returning as expected? For multi-user environments, stay away from `IDENT_CURRENT`, unless you want the other guy's identity (`IDENT_CURRENT` returns a table's latest inserted ID **from any session and any scope**). `SCOPE_IDENTITY()` will work.
p.campbell
`SCOPE_IDENTITY()` should work *most* of the time -- there is apparently a bug involving parallelism in SQL Server 2005/2008: http://blog.sqlauthority.com/2009/03/24/sql-server-2008-scope_identity-bug-with-multi-processor-parallel-plan-and-solution/
LittleBobbyTables
@ p.campbell, If Microsoft fully implemented the spirit of ACID, wrapping a transaction around the insert and select with IDENT_CURRENT should work just fine. I have no idea if they *did* or not. But it *should* work =)
colithium