1
string selectedAreas = getSelectedAreas(areaCounts);

SqlConnection cn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select top 1 [x1] " +
                  "from sometable " +
                  "where sometable.coll = @selectedAreas" +
                  "order by NEWID() ";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.AddWithValue("@selectedAreas", selectedAreas);

What am I doing wrong here?

I get

Must declare the scalar variable for @selectedAreas.

@selectedAreas might become something like:

" 'nyc' or sometable.coll = 'la' or sometable.coll = 'miami' "

Edit:

I added the space as the comment below pointed out. And removed the paramter, like this:

cmd.CommandText = "select top 1 [x1] " +
                  "from sometable " +
                  "where sometable.coll = " + selectedAreas
                  " order by NEWID() ";

Dont know how correct it is but it works for now...

Adam Wenger
  • 17,100
  • 6
  • 52
  • 63
mdc
  • 1,161
  • 6
  • 22
  • 37

1 Answers1

1

It could be the way you are running the command (which you didn't include in your question), such as in this case: Must Declare Scalar Variable

Community
  • 1
  • 1
Tobberoth
  • 9,327
  • 2
  • 19
  • 17