We can insert multiple records from C# to SQL in a single instance. This ultimately saves a number of database requests. Please follow the below steps to achieve this.
Step 1
Create a user-defined table type in SQL.
Example
- CREATE TYPE [dbo].[ShopProduct] AS TABLE(
- [ItemNumber] [int] NULL,
- [ItemCode] [varchar](150) NULL,
- [Name] [varchar](150) NULL,
- [Price] [int] NULL
- )
Step 2
Create a stored procedure to accept the above created table type as input. This can be invoked from C#
- create procedure [dbo].[usp_InsertProducts](@tableproducts ShopProduct readonly)
- as
- begin
- insert into ShopProducts select [ItemCode],[Name],[Price] from @tableproducts
- end
Step 3
Invoke the stored procedure created in step 2 from C# code.
- DataTable dt = new DataTable();
- //Add columns
- dt.Columns.Add(new DataColumn("ItemNumber", typeof(string)));
- dt.Columns.Add(new DataColumn("ItemCode", typeof(string)));
- dt.Columns.Add(new DataColumn("Name", typeof(string)));
- dt.Columns.Add(new DataColumn("Price", typeof(int)));
- //Add rows
- dt.Rows.Add("1000", "Code1", "Phone1", 20000);
- dt.Rows.Add("1001", "Code2", "Phone2", 30000);
- dt.Rows.Add("1002", "Code3", "Phone3", 50000);
- //sqlcon as SqlConnection
- SqlCommand sqlcom = new SqlCommand("usp_InsertProducts", sqlcon);
- sqlcom.CommandType = CommandType.StoredProcedure;
- sqlcom.Parameters.AddWithValue("@tableproducts", dt);
- sqlcom.Parameters.Add(prmReturn);
- sqlcon.Open();
- sqlcom.ExecuteNonQuery();
Screenshot of ShopProducts before code execution.

Screenshot of ShopProducts after execution.


Test CustomerPosted Sep 14, 2023, 10:31 AM
Hello Sir please help me
Rajesh NayakPosted Feb 26, 2023, 4:55 AM
Should not be hard coded
Radovan PodhradskyPosted May 13, 2020, 3:01 AM
Nice feature description, I agree. When you need working example, look at Code Examples article https://code-examples.net/en/q/d7e2cd and Microsoft documentation related to Table-valued parameter in ADO/.NET https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters
Muhammad FayasPosted Aug 18, 2019, 10:14 AM
How do we do this for multiple table entry at the same time?
sibadutta NayakPosted Jun 26, 2019, 6:32 PM
Can you please explain what is prmReturn ?
Salim Zekkour FerhatePosted May 29, 2019, 8:21 PM
Whate prmReturn ??
Viknaraj ManogararajahPosted Jul 19, 2018, 6:46 AM
Nice Article...........
Ardell CraftPosted Jun 29, 2018, 9:58 AM
There's another way to bulk insert records without creating a stored procedure: Create a "SQLBulkCopy" object.
Ankit JaiswalPosted Jun 26, 2018, 4:20 AM
how do we implement this in mvc. if we do not have datatable what else we will use to achieve the same.