views:

259

answers:

2

For some reason my stored procedures are all executing twice! I have a static function that runs an SP given its name and the parameters and fills a datatable.

Public Shared Function RunSP(ByVal spName As String, ByRef spParams As Dictionary(Of String, String), ByRef pDataTable As DataTable) As Integer
    Dim cmd As New SqlCommand
    Dim lAdapter As SqlDataAdapter
    Try
        cmd.Connection = New SqlConnection(ConnectionString)
        cmd.Connection.Open()
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = spName

        For Each item As KeyValuePair(Of String, String) In spParams
            cmd.Parameters.AddWithValue(item.Key, item.Value)
        Next

        cmd.ExecuteNonQuery()
        If Not pDataTable Is Nothing Then
            lAdapter = New SqlDataAdapter(cmd)
            lAdapter.Fill(pDataTable)
        End If
        RunSP = 0
    Catch ex As Exception
        If (Not cmd Is Nothing) Then
            cmd.Dispose()
        End If
        RunSP = -1
    End Try
End Function

Is there something wrong with the code? I've checked with the debugger and the appropriate SPs are definitely only being called once, i.e. this function only runs once for a particular insertion function, but two things are inserted into the table.

+7  A: 

You are executing it once manually (cmd.ExecuteNonQuery()), then the adapter will execute it once (New SqlDataAdapter(cmd)... Fill(...)). Thus twice. Did you mean to use a different command for the adapter?

Marc Gravell
I want to get a DataTable back, is there a way that won't execute the query again, or should I scrap the "ExecuteNonQuery" part?
DisgruntledGoat
Scrap the ExecuteNonQuery part. That's usually for running code that doesn't return rows, such as updates and deletes.
CodeByMoonlight
+5  A: 

You're running the stored procedure twice, one in cmd.ExecuteNonQuery and then a second time when you're running lAdapter.Fill.

CodeByMoonlight