Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi all this is my code for a start.

Sub sqlinsert()

Try

kermitconnection = New SqlConnection("Server=localhost;uid=USERNAME;pwd=PASSWORD;database=DATABASE")

kermitconnection.Open()

Dim cmdinsertsupportitem As SqlCommand

cmdinsertsupportitem = New SqlCommand("Insert employees (lastname,firstname,department) Values (@thelastname,@thefirstname,@thedepartment)", kermitconnection)

cmdinsertsupportitem.Parameters.Add("@thelastname", alastname.text)

cmdinsertsupportitem.Parameters.Add("@thefirstname", afirstname.text)

cmdinsertsupportitem.Parameters.Add("@thedepartment", adepartment.text)

cmdinsertsupportitem.ExecuteNonQuery()

 

kermitconnection.Close()

Catch

End Try

End Sub

I have looked all over and found quite a few examples of getting the Identity after I have done this insert, does anyone know of a way of implementing this into my existing code?

  • *Experts*
Posted

I assume this is SQL server? You'll have to add "SELECT @@IDENTITY" to your SqlCommand and run an actual query, not ExecuteNonQuery. You can use a DataReader or a DataSet - but you need to get the value out. The "SELECT @@IDENTITY" will give you the ID of the last inserted row, in column1 or row1 of your executed statement.

 

You may have to also run "SET NOCOUNT ON" as the first part of your SQL statement as the rowcount of the actual INSERT may cause problems with retrieving the ID (I can't remember).

 

Here's the final SQL statement that should be built (all in one SQL string):

SET NOCOUNT ON
Insert employees (lastname,firstname,department) Values (@thelastname,@thefirstname,@thedepartment)
SELECT @@IDENTITY

 

-Ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...