get last inserted ID with

T

tarscher

Hi all,

I have a database layer (DataSet) I use to attach my controls to. The
dataset is generated via the wizard. I want to know how I can get the
las inserted id I did with one of the queries I defined in that
databaselayer. I know of both @@IDENTITY and scope_identity() but I
can't get the id from that query.

I try:
int lastId = Convert.ToInt16(myDataSetTableAdaptor.GetLastIDQuery());

where GetLastIDQuery() is the query that returns the last id ("SELECT
SCOPE_IDENTITY()") .

All help is greatly appreciated

Regards,
Stijn
 
E

Eliyahu Goldin

Stijn,

You have to do it in the same batch with the insert statement.

"INSERT ...;SELECT SCOPE_IDENTITY()"
 
P

Phil Hall

Dear Stijn

This may not be the most concise way of achiving it but I tend to use
Dataview objects with Dataset tables. You can use code that is easier
to follow with them.

e.g.

da.fill(ds)

'assume da, ds have been declared previously

dim dv as new DataView(ds.tables("tablename"))

dim drv as DataRowView = dv.AddNew

'Now load values into drv with statements like drv("columnName") =
value, except for the column that holds the identity which will be left
as null

drv.EndEdit()

da.Update(ds)

drv now holds the new identity in the appropriate column e.g. new_id =
drv("record_id")

Hope that's useful
 
S

stijngoris

Thanks, that worked. I also changed the query type to scalar.


Eliyahu Goldin schreef:
Stijn,

You have to do it in the same batch with the insert statement.

"INSERT ...;SELECT SCOPE_IDENTITY()"

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]


Hi all,

I have a database layer (DataSet) I use to attach my controls to. The
dataset is generated via the wizard. I want to know how I can get the
las inserted id I did with one of the queries I defined in that
databaselayer. I know of both @@IDENTITY and scope_identity() but I
can't get the id from that query.

I try:
int lastId = Convert.ToInt16(myDataSetTableAdaptor.GetLastIDQuery());

where GetLastIDQuery() is the query that returns the last id ("SELECT
SCOPE_IDENTITY()") .

All help is greatly appreciated

Regards,
Stijn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top