Last two weeks I have been working on developing bulk data manipulations. And even before that I always wondered “What’s the best way to pass an array of values into a SQL Server stored procedure.” One option I found was OPENXML, which I blogged here.
And I was trying out visual studio 2008 and SQL server 2008 these days. And last night I found out that SQL server now support Tabled valued Parameters which allow us to send data tables as parameters to stored procedures. It still uses the same ADO.Net API.
Now I’m going to show how it works. For this I’m using the same scenario which I used in my previous post (reading contents of a folder and saving their information). here i have used sql server 2008 november ctp and visual c# 2008 express edition.
First create the table given below:
CREATE TABLE FileDetails(
FileName varchar(50) PRIMARY KEY,
CreatedDate varchar(50) ,
Size decimal(18, 0) )
Then, we should declare a new Table User Defined Type in the database:
create type FileDetailsType as table
Then create a stored procedure that gets a parameter of the above type, and inserts many rows in a single command.
create procedure InsertFileDetails
@FileDetails FileDetailsType readonly
into FileDetails (FileName, CreatedDate, Size)
select FileName, CreatedDate, Size
Then to execute this procedure, we can create a data table and add the rows in to it. And then pass this data table as parameter to the database.
private static void SaveFileDetail(List<FileInfo> info)
Console.WriteLine(“**********updating with tablevalued parameters****”);
DataTable dt = preparedatatable();
foreach (FileInfo file in info)
DataRow dr = dt.NewRow();
dr = file.Name;
dr = file.CreationTime.ToShortDateString();
dr = (decimal)file.Length;
using (SqlConnection conn = new SqlConnection(“your connection string”))
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = “dbo.InsertFileDetails”;
SqlParameter param = cmd.Parameters.AddWithValue(“@FileDetails”, dt);
Console.WriteLine(“Completed Updating the database”);
Now that’s cool isn’t it????