-1

I'm getting an error on ExecuteScalar(). It says I must declare the scalar variable @PicID. How could I declare a scalar varaible? Or am I doing this entire function incorrectly?

 public int GetTotalNoVotes(int PicRating, int PicID)
    {
        //get database connection string from config file 
        string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"];

        SqlConnection conn = new SqlConnection(strConectionString);
        conn.Open();

        SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM Ratings WHERE PicRating = @PicRating) AND (PicID = @PicID)", conn);
        oCommand.Parameters.Add("@PictureID", SqlDbType.Int);
        oCommand.Parameters["@PictureID"].Value = PicID;

        oCommand.Parameters.Add("@PicRating", SqlDbType.Int);
        oCommand.Parameters["@PicRating"].Value = PicRating;

        object oValue = oCommand.ExecuteScalar();

        conn.Close();

        if (oValue == DBNull.Value)
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(oValue);
        }
    }
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
CsharpBeginner
  • 1,753
  • 8
  • 38
  • 68
  • 2
    There is a shortcut for adding parameters to SqlCommand: oCommand.Parameters.Add("@PictureID", SqlDbType.Int).Value = PicID; –  Nov 21 '11 at 01:02

2 Answers2

2

I think you've defined the parameter @PictureId but you've used the variable name @PicId in the query

Try:

SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM Ratings WHERE PicRating = @PicRating) AND (PicID = @PictureID)", conn);       
Martin Booth
  • 8,485
  • 31
  • 31
1

How would I declare a scaler varaible?

here is your declare code

oCommand.Parameters.Add("@PictureID", SqlDbType.Int);
oCommand.Parameters["@PictureID"].Value = PicID;

and in this case , you must change the PictureID to PicID

oCommand.Parameters.Add("@PicID", SqlDbType.Int);
oCommand.Parameters["@PicID"].Value = PicID;
shenhengbin
  • 4,236
  • 1
  • 24
  • 33