“必须为参数声明标量变量”(C#SqlCommand)

时间:2012-10-31 12:22:07

标签: c# sql sqlcommand

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

我在这里做错了什么?

我得到了

  

必须声明@selectedAreas的标量变量。

@selectedAreas可能会变成:

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

编辑:

我在下面的评论中指出了这个空格。并删除了参数,如下:

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

不知道它有多正确,但它现在有用......

1 个答案:

答案 0 :(得分:0)

这可能是您运行命令的方式(您未在问题中包含该命令),例如:Must Declare Scalar Variable