Friday 27 March 2020

php sql_srv get last inserted id


$query = "INSERT INTO test (col1, col2) VALUES (?,?); SELECT SCOPE_IDENTITY()";
$arrParams[]="1";
$arrParams[]="2";
$resource=sqlsrv_query($conn, $query, $arrParams);
...
sqlsrv_next_result
($query); bool fetchStatus = sqlsrv_fetch($query); if(fetchStatus === false) { die( print_r( sqlsrv_errors(), true)); } if(fetchStatus === null) { // Some work when there are no results in the result set } else { $id = sqlsrv_get_field($query, 0); } ...
query needs to have SELECT SCOPE_IDENTITY() for get last insert ID to work
SCOPE_IDENTITY (Transact-SQL)

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope
https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15
https://stackoverflow.com/questions/23491636/grabbing-last-insert-id-sqlsrv
https://stackoverflow.com/questions/23491636/grabbing-last-insert-id-sqlsrv


No comments:

Post a Comment