0

I'm need to get the ID of the last record inserted into my table.

INSERT INTO mytable (Column1, Column2) VALUE ('Test', 'Bob');
SELECT/SET LAST_INSERT_ID() as NewID;
Response.Write rst("NewID") '(for example)

Can it run in one statement, or do I need to run the SELECT LAST_INSERT_ID after the INSERT SQL has ran.

I am using MYSQL and ASP

user692942
  • 16,398
  • 7
  • 76
  • 175
John Moore
  • 511
  • 1
  • 9
  • 23

2 Answers2

1

You need to run it after every statment as it will always returns one id of most recent inserted record.

To achieve your goal, You need to do is, whenever any record inserted to table, get the last id and store it in to any string/table every time and return it from your sproc. This way you get all inserted id at once.

  • Isn't that what the OP is trying to avoid in the first place? Also this is SQL Server **not** MySQL - *"I am using MYSQL and ASP"* – user692942 May 28 '15 at 12:56
  • 1
    I don't have any problems running the "SELECT LAST_INSERT_ID() as NewID", works every time running as two separate statements. I'm just concerned about accuracy, what happens if a new record is inserted bewteen the INSERT INTO and SELECT LAST_INSERT_ID(), the odds must be a billion to one, but is it possible. – John Moore May 28 '15 at 13:10
  • Not sure this is up-vote worthy you've just edited your [original answer](http://stackoverflow.com/revisions/30506961/1) based off what others like BabyDuck have already pointed out. The first answer completely missed the point, this however is closer but not great *(no real explanation)*. – user692942 May 28 '15 at 14:13
0

I think that you need to run 2 procedure, first insert and then select order by id desc

Fabio Pellerito
  • 204
  • 1
  • 9