Retrieve newly inserted record ID?

1

11D.Universe

I'm using the Insert button in a DetailsView to insert a record into a
SQL table. I've got part of what I need to recover the record ID...

The INSERT COMMAND is:
InsertCommand="INSERT INTO [inventory] ([Active], ...) VALUES
(@Active...); select SCOPE_IDENTITY();"

The Select Command is:
SelectCommand="SELECT * FROM [inventory] where [inventoryID] =
@identity ORDER BY [InventoryID] DESC"

The Insert Parameters are:
<InsertParameters>
<asp:parameter Name="Active" Type="Boolean" />
...
<asp:QueryStringParameter Name="@identity"
Direction="Output" Type="Int32" />
</InsertParameters>

The Select Parameters are:
<asp:parameter Name="identity" Type="Int32" />

I know I'm supposed to put some code in the SqlDataSource1_Inserted
sub, but not sure what code is needed to get the InventoryID from the
inserted record.

Am I on the right track??

Any help would be appreciated...
 
R

Riki

11D.Universe said:
I'm using the Insert button in a DetailsView to insert a record into a
SQL table. I've got part of what I need to recover the record ID...

The INSERT COMMAND is:
InsertCommand="INSERT INTO [inventory] ([Active], ...) VALUES
(@Active...); select SCOPE_IDENTITY();"

The Select Command is:
SelectCommand="SELECT * FROM [inventory] where [inventoryID] =
@identity ORDER BY [InventoryID] DESC"

The Insert Parameters are:
<InsertParameters>
<asp:parameter Name="Active" Type="Boolean" />
...
<asp:QueryStringParameter Name="@identity"
Direction="Output" Type="Int32" />
</InsertParameters>

The Select Parameters are:
<asp:parameter Name="identity" Type="Int32" />

I know I'm supposed to put some code in the SqlDataSource1_Inserted
sub, but not sure what code is needed to get the InventoryID from the
inserted record.

Am I on the right track??

Yes, you are.

Put this code in SqlDataSource1_Inserted (VB.NET):

If (e.Exception IsNot Nothing) Then
' log error or show error
e.ExceptionHandled = True
Return
End If
Dim InventoryID As Integer =
CInt(e.Command.Parameters("@identity").Value)

You may have to modify your INSERT command to match the parameter:
select SCOPE_IDENTITY AS @identity;

Riki
 

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,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top