Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with getting last inserted ID #32

Closed
ghost opened this issue Apr 11, 2014 · 8 comments
Closed

Problem with getting last inserted ID #32

ghost opened this issue Apr 11, 2014 · 8 comments

Comments

@ghost
Copy link

ghost commented Apr 11, 2014

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.

@ghost
Copy link
Author

ghost commented Apr 28, 2014

Is anyone else having the same problem? Or is this not a bug?
Any response is appreciated.

Cheers.

@Dalorzo
Copy link

Dalorzo commented Apr 28, 2014

I would like to recommend POST these type of questions in StackOverflow, there is tag for this project:
http://stackoverflow.com/questions/tagged/node-mssql

I did this I created this table:

CREATE TABLE demoTable(
    id INT IDENTITY(1,1) NOT NULL,
    someValue   VARCHAR(20) NOT NULL,
)

Then I created this demo code and it worked fine:

var connection = new self.sql.Connection(DBConfig, function (err) {
        console.log("Demo Query");
        var query = "INSERT INTO demoTable(someValue) values ('someValue') ";
        var request = new sql.Request(connection);
        request.query(query, function(err, data) {
            console.log("Request Query 1 - Insert");
            if (!err)
            {
                var str = "SELECT @@IDENTITY AS 'identity'";
                request = new sql.Request(connection);
                request.query(str, function(suberr, subdata)
                {
                    console.log("Querying @@Indentity : ");
                    console.log(subdata);   // -> RETURNED NOTHING
                });
            }
            else{
                console.log(err);
            }
        });
    });

@patriksimek
Copy link
Collaborator

Closing due to inactivity.

@Loksly
Copy link

Loksly commented Jun 2, 2016

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:

var query = "INSERT INTO demoTable(someValue) values ('someValue')";
query = query + ';select @@IDENTITY AS \'identity\''; // ---- this is what worked

request.query(str, function(suberr, subdata){
    console.log("Querying @@IDENTITY : ");
    console.log(subdata[0].identity);   // -> RETURNED VALUE
});

@andr333v
Copy link

Hi guys,

I know this issue is closed but still decided to ask. I currently need the same thing as the author of the thread. I need to insert a row and as a result get back its id.

Now, I see that the answers here would do the job but is it really true that this functionality is not part of the mssql library? I mean I kind of expected when I insert a row to get back what's been inserted in the result along with any fields that were set upon inserting (like id).

@ocpuso , you probably did research before posting this so what do you think?

@itdpong
Copy link

itdpong commented Apr 13, 2018

I am having the same question. there are no ways to return the last insert id
nomatter the select statement is execute in the same connection with insert query, it always return nothing. So how can your guys get the last insert id????

		var dbConn = new sql.Connection(dbIntra,function (err) {
			var tran = new sql.Transaction(dbConn);
			tran.begin(function (error) {
				var rollBack = false;
				tran.on('rollback',function (aborted) {
					rollBack = true;
				});
				var query="INSERT INTO [dbo].[voices] ([userid],[type],[number],[recording_date],[remark],[create_time]) VALUES (" + req.user.user_id + ", '" + req.body.type + "','" + req.body.number+ "',convert(datetime, '" + req.body.recording_date + " 00:00:00', 120) ,'" + req.body.remark + "', GETDATE());";
				//query+="SELECT SCOPE_IDENTITY() AS id;";
				new sql.Request(tran).query(query,function (err, recordset) {
					//console.log(recordset);
					if (err) {
						if (!rollBack) {
							tran.rollback(function (err) {
								res.json({"success": false, "msg":"Rollback:" + err});
							});
						}
					} else {
						var str = "SELECT SCOPE_IDENTITY() AS id";
						request = new sql.Request(dbConn);
						request.query(str, function(suberr, subdata){
							console.log(subdata);   // -> RETURNED NOTHING
						});

						tran.commit().then(function (recordset) {
							console.log(recordset);
							res.json({"success": true, "msg":"Data is inserted successfully!"});
						}).catch(function (err) {
							res.json({"success": false, "msg":'Error in transaction commit ' + err});
						});
					}
				});
			});
		});

@amdp

This comment has been minimized.

@dhensby
Copy link
Collaborator

dhensby commented Apr 8, 2019

This was answered 3 years ago #32 (comment)

@tediousjs tediousjs locked as resolved and limited conversation to collaborators Apr 8, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants