Home > Backend Development > C++ > How Can C# Efficiently Bulk Insert Parameterized Data into a Database?

How Can C# Efficiently Bulk Insert Parameterized Data into a Database?

Patricia Arquette
Release: 2025-01-03 21:18:09
Original
991 people have browsed it

How Can C# Efficiently Bulk Insert Parameterized Data into a Database?

Bulk Insert Parameterized Variables into Database using C#

Inserting numerous parametrized variables into a database efficiently is a common challenge faced by developers. C# offers a solution using table-valued parameters and stored procedures to insert multiple rows in a single query.

Creating the User-Defined Table Type

Begin by creating a user-defined table type that mirrors the structure of the target database table:

CREATE TYPE MyTableType AS TABLE
(
    Col1 int,
    Col2 varchar(20) 
)
GO
Copy after login

Defining the Stored Procedure

Next, create a stored procedure that accepts the newly created table type as an input parameter:

CREATE PROCEDURE MyProcedure
(
    @MyTable dbo.MyTableType READONLY -- NOTE: table valued parameters must be Readonly!
)
AS

INSERT INTO MyTable (Col1, Col2)
SELECT Col1, Col2 
FROM @MyTable

GO
Copy after login

This stored procedure will insert the data from the @MyTable table type into the MyTable table in the database.

Executing the Stored Procedure from C#

Finally, execute the stored procedure from C# using the following code:

DataTable dt = new DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Columns.Add("Col2", typeof(string));

// Fill your data table here

using (var con = new SqlConnection("ConnectionString"))
{
    using(var cmd = new SqlCommand("MyProcedure", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@MyTable", SqlDbType.Structured).Value = dt;
        con.Open();
        cmd.ExecuteNonQuery();
    }
}
Copy after login

Advantages of Using Table-Valued Parameters

Using table-valued parameters offers several advantages:

  • Efficient: A single query replaces multiple insert statements, significantly improving performance.
  • Parameterized: Data is passed in a parameterized manner, reducing the risk of SQL injection attacks.
  • Extensible: The user-defined table type can be modified to match different scenarios without altering the stored procedure.

The above is the detailed content of How Can C# Efficiently Bulk Insert Parameterized Data into a Database?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template