Friday, March 9, 2012

How to read just inserted auto incremented primary key to use it as parameter?

Hi. After inserting data (new row) by using DetailsView control, how to read auto incremented primary key (identity) of this new row from sql database to use it as parameter passed to stored procedure?

Or in other way. I need to insert new row (let's call them parent row) in one table by using DetailsView control. This is quite easy. But after inserting I need to read primary key of this new row to insert new child row in other table. Both tables are in relation. How to do this? Any suggestions? Pawel.

Hi Pawelek,

Since the ID (primary key) is configured as an auto incremented field, the last row inserted will always have the maximum number.

You could write a stored procedure which selects the maximum ID number ( SELECT max(ID) from ParentRowsTable ) and returns it.
Then in your code you can execute the SP after you insert a row and you get the max. ID of the parent rows.

Greets,

Wim

|||Hi. I'm afraid that this is a risky business. What if in the same time some other people will insert new row which becomes row with maximum number? Is it possible such situation? Regards. Pawel.|||

Hi. you can return the@.@.IDENTITY

INSERT INTO [dbo].[table] (name, phone)VALUES ("test", "tttt")Return@.@.IDENTITY
|||I would recommend using SCOPE_IDENTITY() instead of @.@.IDENTITY. The former maintains the scope. Check out BOL for more info.

No comments:

Post a Comment