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



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




.



Relevant Pages

  • RE: How Do I Extract Data from my Form to load new table records?
    ... Steve: I have adapted your code as follows, but am ... Dim strSQL As String ... Open a "template table with a number of predefined "standard" rows ... file has 10 records in it, then every time I execute this, I would be adding ...
    (microsoft.public.access.formscoding)
  • Re: Execute Method for Find Object
    ... During each iteration of the While loop, if .Execute returns ... Dim strSearch As String, strTerm As String ... Dim intIndex As Integer, intCounter As Integer, intLast As Integer ...
    (microsoft.public.word.vba.beginners)
  • Re: Database Extract Automation
    ... > database to execute JET SQL statements to move the data across. ... > Dim dbWSec 'As DAO.Workspace ... > 'Add code here to make sure UnsecuredDB doesn't ...
    (microsoft.public.access.externaldata)
  • Re: Select several words
    ... .Execute findText:=oldPart, _ ... Word MVP web site http://word.mvps.org ... Dim ChangeDoc As Document, RefDoc As Document ...
    (microsoft.public.word.docmanagement)
  • Re: Looping!
    ... Well, McKirahan, this too takes about 30-35 seconds to execute! ... Now for the drop-downs - the no. ... the strSQL2 queries to populate the drop-downs. ... Dim strSQL1,strSQL2 ...
    (microsoft.public.inetserver.asp.db)