我收到异常“必须声明标量变量”@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);
我已经宣布了变量。我的查询中有任何缺陷吗?
答案 0 :(得分: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
答案 1 :(得分:1)
您已声明@straccountid
但未作为SQL的一部分。 SQL服务器只能看到您发送给它的内容。您最好使用SQLCommand和参数安全地构建您的select语句。 This post有例子。