2012-12-25 18 views
-3

我無法執行標量查詢。獲取「不正確的語法附近」=「」的例外。問題是我想從表中訪問性別,然後在數據讀取器的幫助下更新另一個表。Exectue標量查詢錯誤c#

SqlConnection con1 = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Muneeb\Documents\Visual Studio 2012\Projects\Dwh_Class_Project\Dwh_Class_Project\Centralised_db.mdf;Integrated Security=True"); 
string gender_get; // get the gender from the database 
SqlCommand cmdgen = new SqlCommand(); 
cmdgen.CommandText = "select top 1 gender from name_lookupwhere name= 'ahmed'"; 

con1.Open();  
cmdgen.Connection = con1; 
string g = ((string) cmdgen.ExecuteScalar()); 

MessageBox.Show("test" + g); 
+1

是在'name_lookupwhere'缺少的空間僅僅是抄寫錯誤? –

+4

由於這個原因,投票關閉太過本地化。 –

回答

2

你缺少一個空間:name_lookupwhere應該name_lookup where

另外,請注意,您正在執行一個返回一行的select top 1 ...,但運行ExecuteScalar的查詢,該查詢需要返回單個值。

+0

他們正在查詢「select top 1 gender」,這確實是一個單一的值。 =) –

+0

我刪除了top1,但仍然是拋出異常。沒有'top 1'的 –

+0

更糟;您可能會返回更多行。顧名思義,ExecuteScalar需要一個標量值。 – GolfWolf

0

查詢中缺少空格。 嘗試:

cmdgen.CommandText = "select top 1 gender from name_lookup where name = 'ahmed'"; 
+0

非常感謝!我從查詢運行器粘貼查詢,以便在where命令中給出問題。 –

0

應該這樣做:

using(SqlConnection con1= new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Muneeb\Documents\Visual Studio 2012\Projects\Dwh_Class_Project\Dwh_Class_Project\Centralised_db.mdf;Integrated Security=True")) 
    { 
     using(SqlCommand cmdgen = new SqlCommand("select top 1 gender from name_lookup where name= @name", con1)) 
     { 
      cmdgen.AddWithValue("@name", "ahmed"); 

      string g = ((string) cmdgen.ExecuteScalar()); 

      MessageBox.Show("test" + g); 
     } 
    } 
+0

正在工作。 是一個錯誤,因爲我直接粘貼查詢並沒有注意到where子句沒有分開。 –