Home > Backend Development > C++ > How Can I Efficiently Insert Multiple Rows with Parameterized Queries in C#?

How Can I Efficiently Insert Multiple Rows with Parameterized Queries in C#?

DDD
Release: 2025-01-01 04:54:10
Original
518 people have browsed it

How Can I Efficiently Insert Multiple Rows with Parameterized Queries in C#?

Inserting Multiple Parameterized Rows with a Single Query in C#

Parameterized queries allow developers to execute SQL statements without hard-coding values, preventing SQL injection attacks and improving performance. Inserting multiple rows with parameterized values can be efficient, especially when using a larger number of rows.

In the provided code, each row is inserted individually, which can be slow. To address this, you can take advantage of table-valued parameters with SQL Server 2008 and above.

Creating a Table-Valued Parameter

First, create a user-defined table type that defines the columns of your data:

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

Creating a Stored Procedure

Next, create a stored procedure that accepts the table-valued parameter:

CREATE PROCEDURE MyProcedure
(
    @MyTable dbo.MyTableType READONLY 
)
AS

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

GO
Copy after login

Note that the @MyTable parameter is marked as READONLY because table-valued parameters must be read-only.

Executing the Stored Procedure with a DataTable

Finally, execute the stored procedure from C# using a DataTable:

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

By using table-valued parameters, you can insert multiple rows with a single parameterized query, significantly improving performance.

The above is the detailed content of How Can I Efficiently Insert Multiple Rows with Parameterized Queries in C#?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template