Take the 2-minute tour ×

This question already has an answer here:

I want to get last inserted id of particular table. can any one tell me how i can get that? we have mysql_insert_id() in mysql. Do we have similar kind of function in sql server 2008?

share|improve this question

marked as duplicate by nawfal, bobs, spajce, Roman C, Graviton Feb 25 '13 at 3:43


2 Answers 2

up vote 0 down vote accepted

I made this function to make it easy :)... if you have more then one db resource just pass that into the mssql_query request. This will retrieve the last unique id generated on that resource connection.

mssql_query("insert into data(name) values('bob')");
$id = getLastId();

function getLastId() {
    $result = mssql_fetch_assoc(mssql_query("select @@IDENTITY as id"));
    return $result['id'];
share|improve this answer
You might want to look into SCOPE_IDENTITY too, since both @@IDENTITY and SCOPE_IDENTITY work in a slightly different way. –  Sour Lemon Sep 21 '11 at 6:47
In your solution i require to run an extra query.Can't we do this without running an extra query in system? –  SLAYER Sep 22 '11 at 4:01
nope. its only on inserts so will not be an issue. also since it uses the same database link it really wont make a difference. You could write a stored procedure that can return whatever you want back but this is easier if you don't need it. –  duante Sep 22 '11 at 21:04

something like this works very nicely

$sql = "insert into tables(field) values (value);SELECT SCOPE_IDENTITY()";
$db = getConnection();
$results = mssql_fetch_assoc(mssql_query($sql));
share|improve this answer
