2013-05-09 118 views
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); 

我已经声明的变量在我的查询中是否有任何缺陷?

+7

你声明变量的代码在哪里? – 2013-05-09 22:15:48

+0

无论你声明它,SQL都没有看到它 - 你的查询应该有一个'DECLARE @strAccountID varchar(50)'或类似的东西,在某处......它是一个存储过程吗? – 2013-05-09 22:17:56

+0

可能只是一个首选项,但我发现全大写的SQL很难阅读。不是'SELECT gub.Btn,gup.cust_UserName,gup.Email FROM gbs_USER_BTN gub,gbs_USER_PROFILE gup WHERE ...'更容易在眼睛上? – 2013-05-09 22:23:33

回答

1

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

+0

谢谢你的答复。我使用了相同的参数化查询,并将带有标记“AddWithValue”的参数添加到cmd中,但是如果我看到语句oCmd.CommandText = sSQL;,当我尝试检查@accuntId的值仍然没有分配值 – user1567194 2013-05-09 22:43:04

+0

你可以举一个你现在的代码是什么样子的例子吗?当你执行查询时,你仍然得到相同的错误? – Adrian 2013-05-09 22:46:13

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

下面是关于如何创建Parametized查询链接:http://www.dotnetperls.com/sqlparameter

+0

我喜欢你的回答,而不是我自己的回答,尽管我们指向相同的方向。试图从iPhone写这些答案是不容易的:) – Adrian 2013-05-09 22:50:02

+0

感谢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 – user1567194 2013-05-09 22:50:38

+0

Adrian,您指出他的方向正确,并在iPhone上为您打字+1! – 2013-05-09 22:51:15