【问题标题】:Must declare a scalar variable必须声明一个标量变量
【发布时间】:2013-05-04 12:48:30
【问题描述】:

我收到异常“必须声明标量变量”@strAccountID”

string @straccountid = string.Empty;

sSQL =
"SELECT GUB.BTN,
       GUP.CUST_USERNAME,
       GUP.EMAIL
FROM   GBS_USER_BTN         GUB,
       GBS_USER_PROFILE     GUP
WHERE  GUB.CUST_UID = GUP.CUST_UID
       AND GUB.BTN = '@straccountID'
ORDER BY
       CREATE_DATE DESC"

@straccountid = strAccountID.Substring(0, 10);

针对数据库运行查询的代码

    try
                {
                    oCn = new SqlConnection(ConfigurationSettings.AppSettings["GBRegistrationConnStr"].ToString());
                    oCn.Open();
                    oCmd = new SqlCommand();      
oCmd.Parameters.AddWithValue("@strAccountID", strAccountID);  

                    oCmd.CommandText = sSQL;
                    oCmd.Connection = oCn;
                    oCmd.CommandType = CommandType.Text;

                    oDR = oCmd.ExecuteReader(CommandBehavior.CloseConnection);

我已经声明了变量。我的查询有问题吗?

【问题讨论】:

  • 声明变量的代码在哪里?
  • 无论你在哪里声明它,SQL 都看不到它 - 你的查询应该有一个 DECLARE @strAccountID varchar(50) 或类似的东西,某处......它是一个存储过程吗?
  • 可能只是一种偏好,但我发现全大写 SQL 很难阅读。 SELECT gub.Btn, gup.cust_UserName, gup.Email FROM gbs_USER_BTN gub, gbs_USER_PROFILE gup WHERE ... 不是更舒服吗?
  • @AdamPlocher 我刚刚添加了代码
  • 能否包含实际对数据库运行 SQL 语句的代码?

标签: c# sql parameters


【解决方案1】:

首先摆脱这两行:

string @straccountid = string.Empty;
@straccountid = strAccountID.Substring(0, 10);

然后试试这段代码:

string strAccountID = "A1234"; //Create the variable and assign a value to it
string AcctID = strAccountID.Substring(0, 10);

oCn = new SqlConnection(ConfigurationSettings.AppSettings["GBRegistrationConnStr"].ToString());
oCn.Open();
oCmd = new SqlCommand();        

oCmd.CommandText = sSQL;
oCmd.Connection = oCn;
oCmd.CommandType = CommandType.Text;
ocmd.Parameters.Add("straccountid", AcctID); //<-- You forgot to add in the parameter
oDR = oCmd.ExecuteReader(CommandBehavior.CloseConnection);

这是一个关于如何创建参数化查询的链接:http://www.dotnetperls.com/sqlparameter

【讨论】:

  • 我更喜欢你的回答而不是我自己的回答,尽管我们指向同一个方向。尝试用 iPhone 写出这些答案并不容易 :)
  • 感谢 kram。我尝试运行代码并查看输出,但仍未设置该值: SELECT GUB.BTN,GUP.CUST_USERNAME,GUP.EMAIL from GBS_USER_BTN GUB,GBS_USER_PROFILE GUP WHERE GUB.CUST_UID = GUP.CUST_UID AND GUB.BTN = @straccountid ORDER BY CREATE_DATE DESC
  • 阿德里安你指出了他正确的方向,并为你在 iPhone +1 上打字!
  • 我确信一旦我们将值添加到命令对象中,sql 应该会获取没有发生的值。
  • @user1567194 - 您是否为 strAccountID 变量赋值?
【解决方案2】:

您已声明 @straccountid,但不是 SQL 的一部分。 SQL 服务器只看到您发送给它的内容。您最好使用SQLCommand 和参数来安全地构建您的选择语句。 This post 有例子。

【讨论】:

  • 感谢您的回复。我使用相同的参数化查询并将带有标签“AddWithValue”的参数添加到 cmd 但如果我看到语句 oCmd.CommandText = sSQL;,当我试图检查@accuntId 的值仍然没有被分配
  • 你能举例说明你的代码现在是什么样子吗?当您执行查询时,您是否仍然收到相同的错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
相关资源
最近更新 更多