将DataTable传递到存储过程中,有更好的方法吗?

3

数据表格是否可以以某种方式传递到SQL Server 2005或2008中?

我知道标准方法似乎是将XML传递给存储过程。并且可以轻松将数据表转换为XML以执行此操作。

那么将.NET对象传递到存储过程中呢?这可能吗?

我记得在2008年听说过SQL和CLR在某种程度上可以一起使用,但我从未理解过.或许这意味着您可以在存储过程中引用.NET对象?

2个回答

8
你可以在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 年不起作用 :-( - marc_s
我们正在使用2008。我已经把它发送给我的老板们了,也许他们会听取意见。这比从数据表中传递XML更容易,对吧? - punkouter
在2005年的问题上,你抓得很好。我认为这比传递XML更容易。它的另一个很好的用途是当你要向存储过程传递一系列项目时。以前常用的做法是制作一个ID的分隔列表,然后将它们传递并在存储过程中解析它们。使用表类型,您可以传递包含数据的表,然后像普通表一样JOIN到它上面。非常好的东西。 - Paul Kearney - pk
他们阅读了这篇文章并决定使用它。给我免费饮料! - punkouter

0

否则您可以选择 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接