"必须声明标量变量"错误

时间:2014-02-08 13:56:22

标签: c# sql-server

  

必须声明标量变量“@Id”

SqlConnection con = new SqlConnection(@"connectionstring");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT Goal from Planning WHERE Id = @Id");
int goal = (int)cmd.ExecuteScalar();

有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

因为您在Id中声明了SqlCommand参数,但未添加任何值。

当你在CommandText财产中分配文字时,你不需要使用()

cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", YourIdValue);
int goal = (int)cmd.ExecuteScalar();

还可以使用using statement来处置您的SqlConnectionSqlCommand

这是一个完整的例子;

using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand())
{
     cmd.Connection = con;
     cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
     cmd.Parameters.AddWithValue("@Id", YourIdValue);
     try
     {
         conn.Open();
         int goal = (int)cmd.ExecuteScalar();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
}

答案 1 :(得分:2)

您应该为参数

指定一个值
cmd.Parameters.AddWithValue("@Id", value);