Insert collection of data to sql table using c#
insert collection of data in SQL table is called bulk data manipulations, this is the simple and best way to add multiple row with the single collection now define a step's to easy to understand
1- You make a user defined table types
CREATE TYPE [dbo].[TTMultiRowCollection] AS TABLE(
[ID] [int] NULL,
[Name] [varchar(50)] NULL,
)
2- Create SP and take parameter table type as well as READONLY keyword.
CREATE PROCEDURE [dbo].[AddMultiRow](@MultiRowCollection TTMultiRowCollection READONLY)
AS
BEGIN
INSERT INTO [User](ID,Name)
SELECT ID, Name FROM @MultiRowCollection
END
3- Create table in c# for passing the sql
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "Dawood");
table.Rows.Add(2, "Ahmed");
4- Connect to SQL server and passing the table from stored procedure
using (SqlConnection con = new SqlConnection(connecton))
{
using (SqlCommand cmd = new SqlCommand("AddMultiRow"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@AudioCollection", audioColl);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
1- You make a user defined table types
CREATE TYPE [dbo].[TTMultiRowCollection] AS TABLE(
[ID] [int] NULL,
[Name] [varchar(50)] NULL,
)
2- Create SP and take parameter table type as well as READONLY keyword.
CREATE PROCEDURE [dbo].[AddMultiRow](@MultiRowCollection TTMultiRowCollection READONLY)
AS
BEGIN
INSERT INTO [User](ID,Name)
SELECT ID, Name FROM @MultiRowCollection
END
3- Create table in c# for passing the sql
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "Dawood");
table.Rows.Add(2, "Ahmed");
4- Connect to SQL server and passing the table from stored procedure
using (SqlConnection con = new SqlConnection(connecton))
{
using (SqlCommand cmd = new SqlCommand("AddMultiRow"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("@AudioCollection", audioColl);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
Comments
Post a Comment