Solved

Auto Increment primary key issue

Posted on 2006-06-28
1
235 Views
Last Modified: 2010-04-23
Hi,
I have a sql server database, and for a primary key I use an auto incrementing integer field.  In my code I create a new row like this...

Dim rowNewRow As DataRow
rowNewRow = Me.DsTheDataSet.TheTable.NewRow
rowNewRow.Item("Field1") = "something"
Me.DsTheDataSet.TheTable.Rows.Add(rowNewRow)

That works fine, but the primary key created for the new row isn't the real key, it's just an auto increment starting from 1.  Once the data is save the primary key updates to the real one.  The thing is I want to be able to use the primary key value before saving the dataset.  Is this possible?

Thanks a lot
0
Comment
Question by:hmcnasty
1 Comment
 
LVL 17

Accepted Solution

by:
ZeonFlash earned 500 total points
ID: 17001787
I can see several possiblities, but none of which are very safe.  First, you can use IDENT_CURRENT('tablename') to get the current identity value...so IDENT_CURRENT('tablename') + IncrementValue [usually 1] would be the NEXT primary key that will be inserted.  You can use this knowledge in tandem with your row creation, but it's a very very very bad idea if someone else could be adding rows at the same time, in which case you would end up with spurious records.

Another method would be to write a stored procedure that inserts your new row and returns the PK.  After you get the PK, you can assign it to the row in the dataset and go about your business.
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question