In C# I'm trying to pass a DataTable as a parameter to an SQL statement. The code I have is below:
protected virtual void DoDeleteRecords(List<Guid> ids)
{
if (ids.Count > 0)
{
DataTable tvp = new DataTable();
tvp.Columns.Add("Id", typeof(Guid));
foreach (Guid id in ids)
{
DataRow row = tvp.NewRow();
row["Id"] = id;
tvp.Rows.Add(row);
}
string sql = string.Format("DELETE FROM MyTable WHERE ID IN ({0})", "@IDTable");
SqlConnection connection = new SqlConnection(CoreSettings.ConnectionString);
using (connection)
{
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter tvpParam = command.Parameters.AddWithValue("@IDTable", tvp);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.IDList";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
However, when command.ExecuteNonQuery is called, I get the following SqlException error:
Must declare the scalar variable "@IDTable"
I understand that this error is normally associated with missing out the parameter value, but as far as I can tell, I have that.
Can anyone see what I'm doing wrong?
Many thanks.
UPDATE I have modified the question to remove crappy SQL injection-rich code from my example.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…