views:

504

answers:

1

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  A: 

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();
}
Paul Kearney - pk
That's in SQL Server **2008** and newer only - doesn't work in 2005 :-(
marc_s
We are using 2008. I sent it to my bosses. maybe they will listen. Its easier than passing in XML from the datatable right?
punkouter
Good catch on the not working in 2005. I think it is easier than passing in XML. Another great use for it is when you are passing in a list of items to a stored procedure. A common practice used to be making a delimited list of ids, then passing them in and parsing them in the stored procedure. With a table type, you can pass in a table containing your data, then JOIN to it like you would a regular table. Good stuff.
Paul Kearney - pk
they read this post and decided to use it.. free drink for me !
punkouter