【问题标题】:"Must declare the scalar variable" for parameter (C# SqlCommand)参数的“必须声明标量变量”(C# SqlCommand)
【发布时间】:2012-10-31 12:22:06
【问题描述】:
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() ";

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

【问题讨论】:

  • SQL 中@selectedAreas 后面需要一个空格。至于你的价值,它是行不通的。
  • ...愚蠢的空间。好的,那我怎样才能让它工作呢?
  • 标准警告:当心这种方法的 SQL 注入。
  • 对于问题的第二部分,也许this question 可能是一个起点。对于您编辑的方法,请找到删除按钮。

标签: c# sql sqlcommand


【解决方案1】:

这可能是您运行命令的方式(您的问题中没有包含),例如在这种情况下:Must Declare Scalar Variable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多