Getting the PK back from an insert sql statement, how?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bob

    Getting the PK back from an insert sql statement, how?

    Using sql 2005 and Vs2005 , snippet below.

    Dim Conn As New SqlConnection(M y.Settings.Conn ectionString.To String)

    Dim cmd As New SqlCommand

    Dim MYPK as long

    Conn.Open()

    cmd.Connection = Conn

    cmd.CommandText = "Insert Into Mytable (Field1,Field2)
    Values('Value1' ,'Value2')"

    "When executed, this inserts only one new row. How can I get the primary key
    of that new record back into variable MYPK

    Any help appreciated,

    Bob




  • Cor Ligthert [MVP]

    #2
    Re: Getting the PK back from an insert sql statement, how?

    Bob,

    Have a look at scope_identity

    Find official documentation, practical know-how, and expert guidance for builders working and troubleshooting in Microsoft products.


    I hope this helps,

    Cor


    Comment

    • Peter Huang [MSFT]

      #3
      RE: Getting the PK back from an insert sql statement, how?

      Hi Bob,

      Here is link for your reference.
      320141 HOW TO: Retrieve an Identity Value from a Newly Inserted Record from
      SQL
      Microsoft Support is here to help you with Microsoft products. Find how-to articles, videos, and training for Microsoft Copilot, Microsoft 365, Windows 11, Surface, and more.


      Best regards,

      Peter Huang
      Microsoft Online Partner Support

      Get Secure! - www.microsoft.com/security
      This posting is provided "AS IS" with no warranties, and confers no rights.

      Comment

      Working...