You may have faced a situation where you need to pass a bunch of rows & columns as a parameter to your Stored Procedure. To overcome from that situation you can pass as many rows and columns to your procedure.
Here in my blog, I’m going to explain to you guys a very simple way to perform this.
First of all, you need a Table
CREATE TABLE MyRecords
(
ID INT PRIMARY KEY IDENTITY(1,1),
FirstName VARCHAR(50),
LastName VARCHAR(50),
DOB DATETIME
)
Next, you need to create a UDT (User Defined DataType)
CREATE TYPE MyType AS TABLE
(
FirstName VARCHAR(50),
LastName VARCHAR(50),
DOB DATETIME
)
Now, let’s create a Procedure where we will pass a table as a parameter.
CREATE PROCEDURE SP_InsertRecords
(
@table MyType READONLY
)
AS
BEGIN
INSERT INTO MyRecords(FirstName,LastName,DOB)
SELECT FirstName,LastName,DOB FROM @table
END
Now, it’s time to write the C# Code.
DataTable dt = new DataTable ();// Please add some rows to DataTable first
SqlConnection con = new SqlConnection(/*Pass Connection string here*/);
con.Open();
SqlCommand cmd = new SqlCommand(“SP_InsertRecords”,con);
cmd.Parameters.Add(“@table”, SqlDbType.Structured);
cmd.Parameters["@table"].Value = dt;
cmd.ExecuteNonQuery();
Now, run your application and pass as many rows as you want at once.
I hope it will help some of you guys.


Praveen Raveendran PillaiPosted Jun 2, 2014, 2:28 AM EDT
Thanks f0r Sharing..!!!
Nagaraj SPosted May 28, 2014, 6:55 AM EDT
Great Concept. Thanks for sharing it.
Leon PuthPosted May 27, 2014, 2:43 AM EDT
but the concept is great and it speeds up data update/insert a lot as you do not need to to call a proc 5000 times, you call it once with a table of 5000 records.
Leon PuthPosted May 27, 2014, 2:42 AM EDT
Word of warning here: in order to modify the used defined data type, you will have to drop all its dependent items, i,e the proc you use it in, so make sure you get its design right before you actually add it to sql, else it will cause you some extra hassle.