目标:使用C#和SQL2008正确设置参数化SQL插入语句
问题:在for循环中使用以下语句,因此必须清除这些值。运行此代码后,它表示语法错误接近250.代码如下
for (int i = 0; i < Rows.Count; i++)
{
cmd.Parameters.Clear();
struct Row = (struct)Rows[i];
sql = "@RowName varchar(250) = null " +
"INSERT INTO " +
"database.dbo.table" +
"(database.dbo.tabe.RowName) " +
"VALUES " +
"(@RowName) ";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);
}
提前感谢您提供更正,意见和建议。
答案 0 :(得分:2)
您不必在SQL代码中重新声明变量。这应该有效:
sql =
"INSERT INTO " +
"database.dbo.table" +
"(database.dbo.tabe.RowName) " +
"VALUES " +
"(@RowName) ";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);
答案 1 :(得分:2)
struct
是关键字,您不能将其用作类型名称。您不需要首先声明参数,(在这种情况下,从AddWithValue
推断出所有必需的元数据),并且SQL查询中的参数名称必须与您在AddWithValue
中放置的内容相匹配。
for (int i = 0; i < Rows.Count; i++)
{
cmd.Parameters.Clear();
var Row = (MyStruct)Rows[i];
sql = "INSERT INTO " +
"database.dbo.table " +
"(database.dbo.tabe.RowName) " +
"VALUES " +
"(@RowName)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@RowName", Row.RowName);
}