Skip to content

Problem with getting last inserted ID #32

Description

Anybody 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions