Call a stored procedure with parameters, return a datatable

At 4Penny, we have an overly complicated piece of library code that we import into all projects that need data access (primer for that here) but on quick jobs it's not worth the setup. 

Here is a quick piece of code that will call a stored procedure and return a dataset. 

 

Public Shared Sub StoredProcWithParamsNoReturnDataset(strServer As String, strDatabase As String)
  
        ' Create and open the  connection in a using block. This
        ' ensures that all resources will be closed and disposed
        ' when the code exits.
        Using oConn As New SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=true", strServer, strDatabase))
  
            Dim oCmd As SqlCommand = New SqlCommand()
  
            oCmd.Connection = oConn
            oCmd.CommandText = "dd_eConnectError_INS"
            oCmd.CommandType = CommandType.StoredProcedure
  
            ' Create the Command and Parameter objects.
            Dim parameter As SqlParameter
            parameter = New SqlParameter("@sopnumbe", "ORD1234")
            oCmd.Parameters.Add(parameter)
  
            parameter = New SqlParameter("@soptype", "2")
            oCmd.Parameters.Add(parameter)
  
            parameter = New SqlParameter("@errortext", "somthing bad happenned")
            oCmd.Parameters.Add(parameter)
  
            ' Open the connection in a try/catch block.
            ' Create and execute the DataReader, writing the result
            ' set to the console window.
            Try
                oConn.Open()
                 Dim oDA As New SqlDataAdapter()
                oDA.SelectCommand = oCmd
                Dim oDS As New DataSet
 
                oDA.Fill(oDS)
                oDT = oDS.Tables(0)
                
 
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
  
        End Using
  
    End Function

 

 

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences