Home All Groups Group Topic Archive Search About

How to get the primary key back after you done a single line insert?

Author
26 May 2006 5:55 PM
Bob
This is the snippet of code
Dim myConnString As String = "Integrated Security=SSPI;Packet Size=4096;Data
Source=MyServer;" & _

"Initial Catalog=MyDatabase; " & _

"Persist Security Info=False;" & _

"Workstation ID=MyWS"

Dim SQL As String = "Insert Into Mytable (MyField) " & _

"Values (" & 1 & ")"

'this will create a single record when executed and that record will have a
field MYPK which is an autogenerated primary key.

'it is that key I need to retrieve immediately after the creation of the new
record.


Dim MyConn As New SqlClient.SqlConnection

MyConn.ConnectionString = myConnString

Dim Mycommand As New SqlClient.SqlCommand

Mycommand.Connection = MyConn

Mycommand.CommandText = SQL

Dim NewPK As Integer

MyConn.Open()

NewPK = Mycommand.ExecuteScalar

The execute scalar was supposed to return (according to docs) the first
column of the first record of the resultset returned by the query.  So I get
0 because I suppose an insert does not return a resultset, So question is,
how do I get the newly created Primary key of the newly created record in
such a case.



Thanks for any help.

Bob

Author
26 May 2006 6:57 PM
Barry
Bob,

I think your SQL statement should be re-written as

Sim sQL As String =  "Set RowCount On " & _
& "Insert Into Mytable (MyField) " & _
& "Values (" & 1 & ") " & _
& "Select Scope_Identity() as 'ReturnPK'" & _
& "Set RowCount Off"

This should return your PK - providing you are using Identity on your
column as a PK?

HTH

Barry
Author
27 May 2006 3:01 PM
Bob
Thanks Barry, I will try this

Bob
Show quoteHide quote
"Barry" <barry.ocon***@manx.net> wrote in message
news:1148669879.284778.288070@i39g2000cwa.googlegroups.com...
> Bob,
>
> I think your SQL statement should be re-written as
>
> Sim sQL As String =  "Set RowCount On " & _
> & "Insert Into Mytable (MyField) " & _
> & "Values (" & 1 & ") " & _
> & "Select Scope_Identity() as 'ReturnPK'" & _
> & "Set RowCount Off"
>
> This should return your PK - providing you are using Identity on your
> column as a PK?
>
> HTH
>
> Barry
>