Problem with getting last inserted ID
See original GitHub issueAnybody have issues with retrieving the last inserted ID from db after an insert statement?
Assume a table student contains 3 fields (id, age, name). Here’s my code:
var query = "INSERT INTO student(age, tagname) values (6, 'Bob') ";
db = new sql.Request();
db.query(query, function(err, data) {
if (!err)
{
var str = "SELECT @@IDENTITY AS 'identity'";
db = new sql.Request();
db.query(str, function(suberr, subdata)
{
console.log(" this is LAST inserted id : ");
console.log(subdata); // -> RETURNED NOTHING
});
}
The above code returned nothing as the ID eventhough the student record was captured correctly into the db.
OUTPUT
this is last LAST inserted id :
[ { identity: null } ]
I am wondering if there’s something wrong with my code, or if this is a bug. Any feedbacks are appreciated.
PS. If I do another query in between the INSERT and SELECT @@IDENTITY, be it a select query, or insert query, then it would give me the ID that I am looking for.
Issue Analytics
- State:
- Created 9 years ago
- Comments:8
Top Results From Across the Web
Problem with Mysql and using the function last insert ID
By the time you SELECT the last inserted id , another session could have INSERT ed a new id , and that would...
Read more >Issue in getting last inserted Id from table - Help
Dear Folks, I am trying to save my file data in sql database. Table 2 PageContent which have column ,Page Number, Page Content...
Read more >mysqli::$insert_id - Manual - PHP
Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute. In the case...
Read more >[resolved] Get last insert ID of a specific table
I tried to use the tMySQLLastInsertId component, but I still have the problem : for the same iteration, no value returned. I used...
Read more >Problem getting inserted ID via PDO - Slim Framework
I am having a bit of a problem for getting the last id for my insert, i have a customer_id field and its...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Just for the record, as you cannot warranty you are using the same connection of the pool, for both the insert and the select statement, you may choose to use a PreparedStatement or simply use the same query for both of them. Use it like this:
This was answered 3 years ago https://github.com/tediousjs/node-mssql/issues/32#issuecomment-223278558