2011-11-14 143 views
1

我有一個函數,它將填充一個數據表與表的內容。但它顯示了一個令人討厭的無效列名錯誤與我在WHERE子句中給出的值。在SQL服務器的where子句中的無效列值

public static DataTable GetRequests(string empid) 
{ 
    DataTable dt = new DataTable(); 
    string strConnection = ConfigurationManager.AppSettings["connStr"]; 
    using (SqlConnection connection = new SqlConnection(strConnection)) 
    { 
     connection.Open(); 
     SqlCommand sqlcmd = new SqlCommand(); 
     SqlDataAdapter sAdap = new SqlDataAdapter();     
     sqlcmd.Connection = connection; 
     sqlcmd.CommandType = System.Data.CommandType.Text; 
     sqlcmd.CommandText = "Select * from requests Where emp_id=P001";     
     sAdap.SelectCommand = sqlcmd; 
     sAdap.Fill(dt); 
    } 
    return dt;    
} 

現在有了這個我得到的錯誤在

sAdap.fill 

,誤差

invalid column name P001 

我在這難住了。任何想法,爲什麼我面臨這個問題?

回答

5

如果它是一個字符串常量,用單引號括起來。 'P001'還是更好,請將其旁路。

2

您需要圍繞該值的字符串分隔符。更改行:

sqlcmd.CommandText = "Select * from requests Where emp_id='P001'"; 

與單引號P001周圍,你應該沒問題。

+0

aww我討厭它的時候,當我讓自己變傻時,謝謝 – swordfish

1

您需要使用單引號。

where emp_id='P001' 
0

看起來您的P001數據是字符串類型。在將它作爲一個sql字符串提供之前,嘗試用單引號引用它。

sqlcmd.CommandText = "Select * from requests Where emp_id='P001'"; 

如果不工作(不過,)你可以嘗試類似的語句,如:

sqlcmd.CommandText = "Select * from requests Where emp_id like 'P001'"; 
0

你需要圍繞你(apparrently)文本標準用單引號:

sqlcmd.CommandText = "Select * from requests Where emp_id = 'P001'";