Click here to Skip to main content
15,076,465 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, I would appreciate some light in there...
So I'm inserting some data in a database, such as name, phone etc. The table has also an autonumeric ID number that increases on every insert, but I don't really know how to get that exactly ID from the last insertion, I plan to store it on a variable. I was thinking of making a SELECT MAX(id) to get it, but it does not look much ellegant, also I don't know how I would store that value returned from the SELECT into a variable. I would love to know that aswell. Thanks so much beforehand!
CHill60 19-Apr-14 12:27pm
Select max (id) is only fine if there is one and only one user of the database. I'd be interested to know why you want the last id inserted
Bardinek 19-Apr-14 12:58pm
Alright, and how do I manage to put that value returned by the select max to a variable? I'm struggling with that. Got no clue, so far I succeeded on inserting stuffs to gridview or combo box, but I don't know how to get that number on a variable.

And I want the last id inserted because that's the foreign key to another table I've got, that manages the products bought from that person. I'm really new on this, quite clear on how the theory works, but it's the first time I start implementing stuff, so I lack some basics..

Thanks for your help!

You can do it in two ways

1) By select max(id)

Select max(id) from tableName order by id DESC

2)By use of @

After insert query you have to return
Which returns last Inserted ID of a colimn

Insert into tableName.........

select @id

You can retrive it using execute scalar, datatable or dataset, datareader as you wish

For more info.....


Bardinek 20-Apr-14 10:28am
How do I save this result Select max(id) from tableName in a variable?
Nirav Prabtani 21-Apr-14 1:43am

select @MaxID=max(ID) from TableName Order by ID DESC

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900