Thursday, February 05, 2009

Retriving Identity Value after Insert

Database: Microsoft SQL Server
Program IDE: VB.NET 2005

I want to retrive the auto generated identity value after I insert a record into an identity column.

There were a lot of stuff about it but nothing that work work without using a stored procedure.

Basically I enclosed the insert and select into a transaction

The following is what I did
________________________________________________________________


' Add the input parameter and set its properties.
Dim parameter As New Data.SqlClient.SqlParameter("pk", Data.SqlDbType.BigInt)
parameter.Direction = Data.ParameterDirection.Output
cmd.Parameters.Add(parameter)

'set insertSql to somthing u do
cmd.CommandText = "begin transaction" & vbCrLf & insertSql & vbCrLf & "select @pk =cast(scope_identity() as int);" & vbCrLf & "commit transaction"
'added try block 7/10/08
Try

Dim msg = cmd.ExecuteNonQuery()
If Val(msg) = 1 Then
'parameter.Value returns the insert identity
msg = parameter.Value
End If
Catch
'output error
End Try

_____________________________________________________________________________

0 Comments:

Post a Comment

<< Home