Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple parameterized variables to a database in c#

I'm looking to do something simulair toward here: How do I insert multiple rows WITHOUT repeating the "INSERT INTO dbo.Blah" part of the statement? except that in addition towards doing this in one query (faster then several dozen) I also want to do this parameterized as the input comes from the web.

Currently I have

foreach(string data in Scraper){
            SqlConnection conn = new SqlConnection(WebConfigurationManager.AppSettings["ConnectionInfo"].ToString());
            string query = "INSERT INTO DATABASE('web',@data)";
            SqlCommand sqlCommand= new SqlCommand(query, conn);
            sqlCommand.Parameters.AddWithValue("@data", data);
            Command.executeNonQuery(); 
            conn.close();
}

Which is a bit slugish (note the real example has a lot more colums but that would make things more confusing).

like image 578
Thijser Avatar asked Jan 29 '26 22:01

Thijser


2 Answers

Since you are using c# and sql server 2008, you can use a table valued parameter to insert multiple rows to your database. Here is a short description on how to do this:

First, you need to create a user defined table type:

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

Then, you need to create a stored procedure that will accept this table type as a 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

Finally, execute this stored procedure from your c# 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();
    }
}
like image 95
Zohar Peled Avatar answered Jan 31 '26 12:01

Zohar Peled


You can make use of the SQL syntax:

INSERT INTO YOUR_TABLE (dataColumn) VALUES (data1),(data2),(data3)

So loop over your rows you wanna insert and append ",(datax)" to your query and also add the corresponding parameter. Perhaps it helps.

like image 38
Tjasun Avatar answered Jan 31 '26 11:01

Tjasun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!