2013-05-09 47 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