Frage

Objective: Using C# and SQL2008 correctly setup a Parameterized SQL Insert statement

Issue: The following statement is used in a for loop so the values must be cleared. Upon running this code it states there is a syntax error near 250. The code is as follows

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);

}

Thank you in advance for corrections, comments and suggestions.

War es hilfreich?

Lösung

You don't have to re-declare the variable inside the SQL code. This should work:

sql =
    "INSERT INTO " +
        "database.dbo.table" +
            "(database.dbo.tabe.RowName) " +
    "VALUES " +
        "(@RowName) ";

cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);

Andere Tipps

struct is a keyword, you can't use it as a type name. You don't need to declare the parameter first, (all necessary metadata is inferred from AddWithValue in this case) and the parameter name in the SQL query has to match what you put in 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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top