【问题标题】:Execute a SQL Stored Procedure and process the results [closed]执行 SQL 存储过程并处理结果 [关闭]
【发布时间】:2011-05-13 12:32:04
【问题描述】:

在 VB.NET 中,我该如何执行以下操作?

  1. 执行存储过程
  2. 通读返回的DataTable

【问题讨论】:

  • 如果你使用的是2008,可以返回一个表。
  • @Doug - OP 不需要 2008 年来满足他的要求。存储过程的结果可以被客户端应用程序捕获为数据集(我没有足够好的 .net 背景,但在 Delphi 中可以)
  • @Lieven,你是对的。 OP 并不需要 2008 来做他们要求的事情。

标签: vb.net tsql sql-server-2008 stored-procedures


【解决方案1】:

在 .vb 文件的顶部:

Imports System.data.sqlclient

在您的代码中:

'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value

Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure

Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300

'Fill the dataset
Dim DS as DataSet    
adapter.Fill(ds)
connection.Close()   

'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
    Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next

现在基本的东西都没有了,

我强烈建议将实际的 SqlCommand 执行抽象为一个函数。

这是我在各种项目中以某种形式使用的通用函数:

''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),''' 
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
    Dim ds As New DataSet()

    Try
        Dim connection As New SqlConnection(connectionString)
        CMD.Connection = connection

        'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
        If CMD.CommandText.Contains(" ") Then
            CMD.CommandType = CommandType.Text
        Else
            CMD.CommandType = CommandType.StoredProcedure
        End If

        Dim adapter As New SqlDataAdapter(CMD)
        adapter.SelectCommand.CommandTimeout = 300

        'fill the dataset
        adapter.Fill(ds)
        connection.Close()

    Catch ex As Exception
        ' The connection failed. Display an error message.
        Throw New Exception("Database Error: " & ex.Message)
    End Try

    Return ds
End Function

一旦你有了这些,你的 SQL 执行 + 阅读代码就非常简单了:

'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("@productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'

【讨论】:

  • +1 建议抽象成一个函数。
【解决方案2】:

来自MSDN

使用命令对象以编程方式执行返回行的存储过程

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

【讨论】:

    【解决方案3】:

    最简单的方法?有用。 :)

        Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
        Try
            Using connection As New SqlConnection(ConnStrg)
                connection.Open()
                Dim command As New SqlCommand(queryString, connection)
                Dim reader As SqlDataReader = command.ExecuteReader()
                Dim DTResults As New DataTable
    
                DTResults.Load(reader)
                MsgBox(DTResults.Rows(0)(0).ToString)
    
            End Using
        Catch ex As Exception
            MessageBox.Show("Error while executing .. " & ex.Message, "")
        Finally
        End Try
    

    【讨论】:

      【解决方案4】:
      Dim sqlConnection1 As New SqlConnection("Your Connection String")
      Dim cmd As New SqlCommand
      
      cmd.CommandText = "StoredProcedureName"
      cmd.CommandType = CommandType.StoredProcedure
      cmd.Connection = sqlConnection1
      
      sqlConnection1.Open()
      
      Dim adapter As System.Data.SqlClient.SqlDataAdapter
      Dim dsdetailwk As New DataSet
      
      Try
         adapter = New System.Data.SqlClient.SqlDataAdapter
         adapter.SelectCommand = cmd
         adapter.Fill(dsdetailwk, "delivery")
         Catch Err As System.Exception
      End Try
      
      sqlConnection1.Close()
      
      datagridview1.DataSource = dsdetailwk.Tables(0)
      

      【讨论】:

        【解决方案5】:

        我的存储过程需要 2 个参数,我需要我的函数返回一个数据表,这里是 100% 工作代码

        请确保您的程序返回一些行

        Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
            Try
                Connection.Connect()
                debug.print("Look up account number " & AccountNumber)
                Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
                Dim DST As New DataSet
                DP.Fill(DST)
                Return DST.Tables(0)      
            Catch ex As Exception
                Return Nothing
            End Try
        End Function
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-05
          • 1970-01-01
          • 1970-01-01
          • 2014-03-07
          • 2014-06-15
          • 1970-01-01
          • 2023-03-24
          相关资源
          最近更新 更多