newbie wanting way to add a new row to a sql DB

Results 1 to 2 of 2

Thread: newbie wanting way to add a new row to a sql DB

  1. #1
    Join Date
    Dec 1969

    Default newbie wanting way to add a new row to a sql DB

    I&#039;m using a standard SQLcommand.ExecuteNonQuery() to insert a row into a table. This table has 3 columns. <BR><BR>A primary key column that is an autogenerated integer, an nvarchar description column, and an int userID field. <BR><BR>I&#039;ll start off by saying that what I have is working fine. I insert the description in a text box and get the userid from a session variable and pass that to my insert statment. The rows are being inserted like I expect. The problem I&#039;m having is I want to then have the id of the new row without having to go back and do another query to get it. <BR><BR>I insert the row and then have to go back and requery with the text I just entered (which is often ambiguous) to get the primary key of the row I just inserted (the only nonambigous column).<BR><BR>I know this cannot be the correct way to do this. <BR><BR>Any ideas? <BR><BR>Another thought I had was to create the new row as soon as I bring up the webform but before I enter the text. This way, I have the primary key as soon as I load the page. The problem here is if I allow the user to leave the form without saving, I guess I need to delete the new row. <BR><BR>Anyway, I appreciate any help on this.

  2. #2
    Join Date
    Dec 1969

    Default RE: newbie wanting way to add a new row to a sql D

    You can use a select @@Identity statement as long as you do it before you close your connection. That will fetch the last id field of your last inserted record on this connection:<BR><BR> com = New SqlCommand(sql, conn)<BR> com.ExecuteNonQuery()<BR> sql = "SELECT @@IDENTITY AS cid FROM client_contact"<BR> com = New SqlCommand(sql, conn)<BR> Dim cid As Integer = com.ExecuteScalar

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts