Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a generic insert method that insert to many kind of tables, this is the method:

C#
using (SqlConnection connection = new SqlConnection(connectionString))
{
   connection.Open();
   SqlCommand command =
   new SqlCommand(
      "INSERT INTO [" +tableName+ "] (" +columns+ ") OUTPUT INSERTED.ID VALUES (" +data+ ");",
      connection);
   return (int)command.ExecuteScalar();
}


How can i convert it to parameter query?
Posted
Updated 19-May-14 0:27am
v3
Comments
DamithSL 19-May-14 6:29am    
how you build columns?
Rob Philpott 19-May-14 6:31am    
What would be the point of turning into a stored procedure?

1 solution

C#
List<string> columns  = new List<string>() {"Col1", "Col2"};
List<object> data  = new List<object>() {1, DateTime.Now};
var tableName ="Table1";

// above data will pass to the method 
// we can buld the column names as below
var strCol = string.Join(",",columns);
// and set of parameter names like below 
var strParam = string.Join(",", columns.Select(r => "@" + r));
//now we can build the full insert statement 
var sql = "INSERT INTO [" +tableName+ "] (" +strCol+ ") VALUES (" +strParam+ ")";

using (SqlConnection connection = new SqlConnection(connectionString))
{
	connection.Open();
	SqlCommand command = new SqlCommand(sql , connection);
	//adding each parameter with name and value 
	for (int i = 0; i < strParam.Length; i++)
	{
	   cmd.Parameters.AddWithValue(strParam[i], data[i]);
	}
   return (int)command.ExecuteScalar();
}</string></string>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900