Solved

Auto Increment primary key issue

Posted on 2006-06-28
1
234 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

837 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