SQLException必须声明标量变量“@variableName”

时间:2012-04-22 14:29:56

标签: c# sqlexception scalar

我在尝试更新特定行的数据库时遇到一些问题,我收到错误Must declare scalar variable "@lvl"。不太清楚我应该做什么。我是否需要在SQL语句中声明值?

private void button1_Click(object sender, EventArgs e)
{
    GridViewCellInfo grd = (GridViewCellInfo)radGridView1.Rows[0].Cells[0];
    string lvl = grd.Value.ToString(); 

    string sqlPatientCmd =
        @"UPDATE MotorTB
          SET RightColumn = @RightColumnCB, LeftColumn =  @leftColumnCB
          WHERE (Level = @lvl)";
    SqlConnection connString = new SqlConnection(@"Data Source=MERCURY\SQLEXPRESS;Initial Catalog=AsiaDB; Integrated Security=SSPI;User ID=MERCURY\Sophie;");
    try {
        connString.Open();

        SqlCommand sqlCmdStatement = new SqlCommand(sqlPatientCmd, connString);

        GridViewCellInfo grid;
        grid = (GridViewCellInfo)radGridView1.Rows[0].Cells[1];
        string rightColVal = grid.Value.ToString();

        grid = (GridViewCellInfo)radGridView1.Rows[0].Cells[2];
        string leftColVal = grid.Value.ToString();

        sqlCmdStatement.Parameters.AddWithValue("@rightColumnCB", rightColVal);
        sqlCmdStatement.Parameters.AddWithValue("@leftColumnCB", leftColVal);
        sqlCmdStatement.ExecuteScalar();
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
    }

    // Close the connection
    try {
        connString.Close();
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
    }
}

2 个答案:

答案 0 :(得分:2)

您需要将lvl var添加为SqlParamter

sqlCmdStatement.Parameters.AddWithValue("@lvl", lvl);

答案 1 :(得分:1)

@lvl需要作为参数提供或以其他方式在查询中定义。