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, 6:31 AM EDT
Hello Sir please help me
Rajesh NayakPosted Feb 25, 2023, 11:55 PM EST
Should not be hard coded
Radovan PodhradskyPosted May 12, 2020, 11:01 PM EDT
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, 6:14 AM EDT
How do we do this for multiple table entry at the same time?
sibadutta NayakPosted Jun 26, 2019, 2:32 PM EDT
Can you please explain what is prmReturn ?
Salim Zekkour FerhatePosted May 29, 2019, 4:21 PM EDT
Whate prmReturn ??
Viknaraj ManogararajahTOP 100Posted Jul 19, 2018, 2:46 AM EDT
Nice Article...........
Ardell CraftPosted Jun 29, 2018, 5:58 AM EDT
There's another way to bulk insert records without creating a stored procedure: Create a "SQLBulkCopy" object.
Ankit JaiswalPosted Jun 26, 2018, 12:20 AM EDT
how do we implement this in mvc. if we do not have datatable what else we will use to achieve the same.