Passing a DataTable into a Stored Procedure. Is there a better way?

二次信任 提交于 2019-12-10 20:38:45

问题


Can A datatable somehow be passed into SQL Server 2005 or 2008 ?

I know the standard way seesm to be passing XML to a SP. And a datatable can easily be converted to XML somehow to do that.

What about passing a .NET object into a SP ? Is that possible ?

I remember hearing about SQL and CLR working together in 2008 somehow but I never understood.. Maybe that means you can refer to .NET objects within a Stored Procedure ?


回答1:


You can create a User-defined table type in SQL. Then, in the stored procedure, accept a parameter of type (your user-defined table type) and pass in a datatable as it's value to a stored procedure.

Here's some examples from http://msdn.microsoft.com/en-us/library/bb675163.aspx:

In SQL:

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

Then:

// 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();
}



回答2:


Else you can choose SQl Bulk Insert.

I tried , most better way.

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


来源:https://stackoverflow.com/questions/2784851/passing-a-datatable-into-a-stored-procedure-is-there-a-better-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!