Retrieve identity value from inserted record's primary key

∥☆過路亽.° 提交于 2019-12-24 01:18:55

问题


i cannot retrieve the new identity value from an inserted record(via DataAdapter.Update) in my DataRow.

I'm using a strong typed Dataset as DAL. The table i want to update is joinded with other tables in the SelectCommand, hence the designer cannot automatically generate the insert-/update-/delete-commands and also it cannot "Refresh the DataTable" automatically(s. http://msdn.microsoft.com/de-de/library/dex7k4dw%28v=VS.100%29.aspx).

I've tried to set AutoIncrement=true/false on the primary-key's DataColumn but the result is the same: last MAX-ID+1 instead of the actual ID the database generated(SQL-Server 2005 EP; pk datatype:int, Is identity:yes, Identity Increment:1).

This will be the wrong value f.e if another instance of the application inserted a record that the first instance yet not knows and therefore generates an ID that already exists.

To retrieve the new identity from db i've appended following to my insert-command's CommandText:

;SELECT CAST (SCOPE_IDENTITY() AS int) AS newIdRMA 

Also i've tried to add an Output-Parameter to it's parameter-collection:

This is part of my code that updates the database and sets the new ID(that doesn't work):

 Me.dsRMA.RMA.AddRMARow(newRMA) ' adding new row to the (strong typed) DataTable ' 
 numRowsUpdated = daRMA.Update(Me.dsRMA.RMA) ' update via DataAdapter and insert the new record in DB '
 DirectCast(Page, Services).IdRma = newRMA.IdRMA ' this is not the actual value from DB but old Max-ID +1 '

Edit:

this is a screenshot of my TableAdapter's InsertCommand and it's parameter-collection:

Thanks in advance.


回答1:


Here How i do it: I append the following to my insert-command's CommandText:

--Return the new id
SELECT SCOPE_IDENTITY() 

Then I set the "ExecuteMode" of that Query to "Scalar" instead of "NonQuery"

so I could retrive it this way:

newRMA = Me.dsRMA.RMA.AddRMARow()


来源:https://stackoverflow.com/questions/5298230/retrieve-identity-value-from-inserted-records-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!