Search code examples
vb.netstored-proceduresshortcutsqlconnection

VB.net Changing stored procedure within an sql connection


I am making a page that will run multiple stored procedures on load to pre-populate textboxes on a page.

Rather than opening and closing a connection every time I want to use a different stored procedure I wondered if it would be possible to change it multiple times within one connection.

eg this:

Using myConnection1 = New SqlConnection("connectionString")
 myConnection1.Open()
 Dim myCommand As New SqlCommand("storedProdure1", myConnection)
 myCommand.CommandType = CommandType.StoredProcedure

 'additional code here

 End Using

Using myConnection2 = New SqlConnection("connectionString")

 myConnection2.Open()
 Dim myCommand As New SqlCommand("storeProcedure2", myConnection2)
 myCommand.CommandType = CommandType.StoredProcedure

 'additional code here

End Using

could be replaced with something like this:

Using myConnection1 = New SqlConnection("connectionString")
 myConnection1.Open()
 Dim myCommand As New SqlCommand("storedProdure1", myConnection)
 myCommand.CommandType = CommandType.StoredProcedure

 'additional code here

myCommand.alterSqlCommand("storedProcdure2", myConnection)

 'additional code here

 End Using

Thanks in advance


Solution

  • When using normal SQL Commands you can just write:

    myCommand.CommandText = "..."
    

    and change the command while having an open connection. The same should work for Stored Procedures. Just use CommandText to change the StoredProcedure.

    Hope this helps.