将DataTable传递给存储过程.有没有更好的办法?

pun*_*ter 3 sql clr stored-procedures

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

我知道将XML传递给SP的标准方式.并且数据表可以很容易地以某种方式转换为XML来实现.

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

我记得在某种程度上听说过SQL和CLR在2008年一起工作但我从来没有理解过......也许这意味着你可以在存储过程中引用.NET对象?

Pau*_* pk 8

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

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

在SQL中:

CREATE TYPE dbo.CategoryTableType AS TABLE
    ( CategoryID int, CategoryName nvarchar(50) )
Run Code Online (Sandbox Code Playgroud)

然后:

// 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();
}
Run Code Online (Sandbox Code Playgroud)