Solved

Get Primary Key of newly inserted record in SQL Server 2008/VB.net

Posted on 2014-02-20
3
1,697 Views
Last Modified: 2014-02-20
I have code which

- inserts a record into table 1 (this works)
- attempts to grab the primary key value of that record (this does not work)
- inserts a related record into table 2.  I am trying to include the primary key from the earlier insert, but the @@IDENTITY returned is null

The field type of the primary key is "uniqueidentifier"

What am I doing wrong?  Or is there a better way to do this?


 
           Dim cn As New SqlConnection
            Dim cmd As New SqlCommand

            cn = GetConnected()
            cmd.Connection = cn

            cmd.CommandText = sSQL
            cmd.Parameters.Add(New SqlParameter("@FromDate", SqlDbType.DateTime))
             ' etc - more parameters added

            '  This works - the record is added with a visible uniqueidentifier
            cmd.ExecuteNonQuery()

            ' This is where I'm trying to grab the Primary Key, but it returns a null....
            cmd.Parameters.Clear()
            cmd.CommandText = "SELECT @@IDENTITY"
            Dim newID As String = "" & cmd.ExecuteScalar()

            ' ... so all of the record added here have a blank SessionID
            sSQL = "INSERT INTO tblScheduleStuff (Scheduler_SessionID, GenericStuff) SELECT '" & newID & "', Stuff FROM tblTEMPStuff"
            cmd.CommandText = sSQL
            cmd.ExecuteNonQuery()

Open in new window

0
Comment
Question by:mbizup
3 Comments
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
ID: 39873979
@@Identity only works if you set the column to be an Identity column (auto increment integer column). You would need to run a select based on the field values that you have just inserted to get the primary key.
0
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 39874082
You can also use the OUTPUT clause.  I'm not sure how this would work with ADO so you may need to encapsulate the insert logic in a stored procedure and return the resultset.

http://technet.microsoft.com/en-us/library/ms177564.aspx
0
 
LVL 61

Author Comment

by:mbizup
ID: 39874107
Ah - that makes sense.

I added an identity column and it is working correctly now using @@Identity.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now