Skip to content Skip to sidebar Skip to footer

"must Declare Scalar Variable" Error

Must declare the scalar variable '@Id' SqlConnection con = new SqlConnection(@'connectionstring'); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.Comman

Solution 1:

You should give a value to your parameter

cmd.Parameters.AddWithValue("@Id", value);

Solution 2:

Because you declared your Id parameter in your SqlCommand but you didn't add it any value.

And you don't need to use () when you assing a text in your CommandText property.

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

Also use using statement to dispose your SqlConnection and SqlCommand.

Here a complete example;

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

Post a Comment for ""must Declare Scalar Variable" Error"