Click here to Skip to main content
14,427,540 members
Rate this:
Please Sign up or sign in to vote.
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!
Posted
Comments
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!
Rate this:
Please Sign up or sign in to vote.

Solution 2

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 @
@@IDENTITY


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

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

SET @id=SCOPE_IDENTITY()
select @id



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

For more info.....

SCOPE_IDENTITY (Transact-SQL)[^]

identity-and-scope_identity-in-sql-server[^]
   
v2
Comments
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
   
DECLARE @MaxID int

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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100