Solved

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

Posted on 2014-02-20
3
1,682 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
Comment Utility
@@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
Comment Utility
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
Comment Utility
Ah - that makes sense.

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

762 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

13 Experts available now in Live!

Get 1:1 Help Now