why is this code executed twice?

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

    #1

    why is this code executed twice?

    Hi, (already posted but unsolved)

    this code inserts twice the same record. I thin it is due to the "Selet
    Scope_Identity" in the sqlcommand.
    If i remove the Select part, the inserts occurs only once. If i remove the
    line "comd.ExecuteNo nQuery()", then the inserts also occurs once.

    Is there something wrong in my code?

    Thanks
    Bob

    Dim connection As SqlConnection
    Dim comd As SqlCommand
    Dim connectionstr, sql As String
    Dim iden As Integer
    connectionstr =
    ConfigurationMa nager.Connectio nStrings("econn ").ConnectionSt ring.ToString()
    connection = New SqlConnection(c onnectionstr)
    comd = New SqlCommand()
    comd.Connection = connection
    sql = "INSERT INTO table(field,... ) VALUES (@fld,...); SELECT
    SCOPE_IDENTITY( )"
    comd.Parameters .Add("@var1", SqlDbType.NVarC har, 10).Value =
    txtvnm.Text
    ...
    connection.Open ()
    iden = Convert.ToInt32 (comd.ExecuteSc alar())
    comd.ExecuteNon Query()
    connection.Clos e()


  • Stephany Young

    #2
    Re: why is this code executed twice?

    And already solved.

    The line you suspect is the one that is doing the 2nd insert.


    "Bob" <bob@omail.nlwr ote in message
    news:ek64lDtVHH A.868@TK2MSFTNG P05.phx.gbl...
    Hi, (already posted but unsolved)
    >
    this code inserts twice the same record. I thin it is due to the "Selet
    Scope_Identity" in the sqlcommand.
    If i remove the Select part, the inserts occurs only once. If i remove the
    line "comd.ExecuteNo nQuery()", then the inserts also occurs once.
    >
    Is there something wrong in my code?
    >
    Thanks
    Bob
    >
    Dim connection As SqlConnection
    Dim comd As SqlCommand
    Dim connectionstr, sql As String
    Dim iden As Integer
    connectionstr =
    ConfigurationMa nager.Connectio nStrings("econn ").ConnectionSt ring.ToString()
    connection = New SqlConnection(c onnectionstr)
    comd = New SqlCommand()
    comd.Connection = connection
    sql = "INSERT INTO table(field,... ) VALUES (@fld,...); SELECT
    SCOPE_IDENTITY( )"
    comd.Parameters .Add("@var1", SqlDbType.NVarC har, 10).Value =
    txtvnm.Text
    ...
    connection.Open ()
    iden = Convert.ToInt32 (comd.ExecuteSc alar())
    comd.ExecuteNon Query()
    connection.Clos e()
    >

    Comment

    • Cor Ligthert [MVP]

      #3
      Re: why is this code executed twice?

      Hi Bob,

      ...
      connection.Open ()
      iden = Convert.ToInt32 (comd.ExecuteSc alar())
      comd.ExecuteNon Query()
      connection.Clos e()
      Both executeScalar and executeNonQuery are starting the SQL line you have
      told that has to be processed. You have them both in your program, therefore
      it is logical that it is processed twice.

      Cor


      Comment

      Working...