Must declare the scalar variable …

“Must declare the scalar variable …”

Every now and then this error is reported when using parameters in SQL statements.

The two most common reasons for this are:

.1 The parameter is simply misspelled. It is common that when there are many parameters in the parameter list that a misspelled parameter has been missed.

So, for example, running this:

            using (SqlConnection con = new SqlConnection(cs))

            {

      con.Open();

                SqlCommand cmd = con.CreateCommand();

                cmd.CommandText = "SELECT * FROM Categories WHERE CategoryID = @catId";

                cmd.Parameters.Add("@catIdd", System.Data.SqlDbType.Int).Value = 1;

        SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())

                {

                    Console.WriteLine("{0} {1}", rdr[0].ToString(), rdr[1].ToString());

                }

                con.Close();

            }

will cause the following exception to be thrown (since the provided parameter name (@catIdd) is misspelled, i.e. not matching the one in the SQL):

System.Data.SqlClient.SqlException: Must declare the scalar variable "@catId".

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)

   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)

   ...

.2 OleDb classes (OleDbConnection/OleDbCommand etc.) are used. When using OleDb the parameters in the SQL are to be set to ? and not @paramname.

So, for example, running this:

            using (OleDbConnection con = new OleDbConnection(cs))

            {

                con.Open();

                OleDbCommand cmd = con.CreateCommand();

                cmd.CommandText = "SELECT * FROM Categories WHERE CategoryID = @catId";

                cmd.Parameters.Add("@catId", OleDbType.Integer).Value = 1;

                OleDbDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())

                {

               Console.WriteLine("{0} {1}", rdr[0].ToString(), rdr[1].ToString());

                }

                con.Close();

            }

will cause the following exception to be thrown since the provided parameter name in the SQL String (@catId) is wrong. Replace it with ? (… WHERE CategoryID = ?) and it should be fine.

System.Data.OleDb.OleDbException: Must declare the scalar variable "@catId".

   at System.Data.OleDb.OleDbDataReader.ProcessResults(OleDbHResult hr)

   at System.Data.OleDb.OleDbDataReader.NextResult()

   ...