【问题标题】:Passing a DataTable into a Stored Procedure. Is there a better way?将 DataTable 传递给存储过程。有没有更好的办法?
【发布时间】:2010-05-06 22:06:47
【问题描述】:

可以将数据表以某种方式传递到 SQL Server 2005 或 2008 吗?

我知道标准方式似乎是将 XML 传递给 SP。并且数据表可以很容易地以某种方式转换为 XML 来做到这一点。

将 .NET 对象传递给 SP 怎么样?这可能吗?

我记得在 2008 年听说过 SQL 和 CLR 以某种方式协同工作,但我一直不明白。也许这意味着您可以在存储过程中引用 .NET 对象?

【问题讨论】:

    标签: sql stored-procedures clr


    【解决方案1】:

    您可以在 SQL 中创建用户定义的表类型。然后,在存储过程中,接受类型参数(您的用户定义表类型)并将数据表作为其值传递给存储过程。

    以下是来自http://msdn.microsoft.com/en-us/library/bb675163.aspx 的一些示例:

    在 SQL 中:

    CREATE TYPE dbo.CategoryTableType AS TABLE
        ( CategoryID int, CategoryName nvarchar(50) )
    

    然后:

    // Assumes connection is an open SqlConnection object.
    using (connection)
    {
    // Create a DataTable with the modified rows.
    DataTable addedCategories =
      CategoriesDataTable.GetChanges(DataRowState.Added);
    
    // Configure the SqlCommand and SqlParameter.
    SqlCommand insertCommand = new SqlCommand(
        "usp_InsertCategories", connection);
    insertCommand.CommandType = CommandType.StoredProcedure;
    
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
        "@tvpNewCategories", addedCategories);
    tvpParam.SqlDbType = SqlDbType.Structured;
    
    // Execute the command.
    insertCommand.ExecuteNonQuery();
    }
    

    【讨论】:

    • 仅在 SQL Server 2008 和更新版本中 - 在 2005 年不起作用 :-(
    • 我们用的是2008。我把它发给了我的老板。也许他们会听。它比从数据表中传入 XML 更容易吧?
    • 很好地抓住了 2005 年不工作的情况。我认为这比传入 XML 更容易。它的另一个重要用途是当您将项目列表传递给存储过程时。一种常见的做法是制作一个分隔的 id 列表,然后将它们传入并在存储过程中解析它们。使用表类型,您可以传入一个包含数据的表,然后像普通表一样加入它。好东西。
    • 他们阅读了这篇文章并决定使用它.. 给我免费饮料!
    【解决方案2】:

    否则,您可以选择 SQl 批量插入。

    我试过了,最好的办法。

    enter code here
    
      Using dbConn As New SqlConnection(connectionStr)
                    dbConn.Open()
                    countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
    
    
    
                    Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(dbConn)
                        bulkcopy.DestinationTableName = "[dbo].[DocumentScan]"
                        Try
                            ' Write from the source to the destination.
                            bulkcopy.WriteToServer(newDataTable)
    
                        Catch ex As Exception
                            Console.WriteLine(ex.Message)
                        End Try
                        Dim countEnd As Long = _
                      System.Convert.ToInt32(commandRowCount.ExecuteScalar())
    
    
                    End Using
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多