0

我收到异常“必须声明标量变量”@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);

我已经声明了变量。我的查询有任何缺陷吗?

4

2 回答 2

2

首先摆脱这两条线:

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

于 2013-05-09T22:43:36.117 回答
1

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

于 2013-05-09T22:39:23.987 回答