Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last inserted id in sql server 2008 [duplicate]

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?

like image 533
Rukmi Patel Avatar asked Dec 28 '22 13:12

Rukmi Patel


2 Answers

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));
$lastid=$results['computed'];
like image 189
darrellbooker Avatar answered Jan 10 '23 21:01

darrellbooker


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'];
}
like image 20
duante Avatar answered Jan 10 '23 21:01

duante