数据类型text和varchar在C#中等于运算符不兼容

时间:2015-01-11 14:38:39

标签: c#

我正在尝试从employeeTable访问数据empname,但我写的代码给了我以下错误:

  

数据类型text和varchar在等于运算符中不兼容。

请建议解决方案

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string Connection = "Data Source=(local);Initial catalog=Test;Integrated Security=true";
    string Query = "SELECT * FROM  EmployeeTable WHERE empname='" + comboBox1.Text + "' ;";

    SqlConnection conn = new SqlConnection(Connection);
    SqlCommand cmd = new SqlCommand(Query, conn);

    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())     
    {
        textBoxEmpName.Text = reader["EmpName"].ToString();
    }
}

4 个答案:

答案 0 :(得分:27)

您无法将文本与varchar进行比较,但作为此问题的未来任何人的答案,只需将文本列转换为查询的varchar。

SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = '" + comboBox1.Text + "' ;";

始终使用parameters

SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = @comboBox";

答案 1 :(得分:1)

如果目标字符串大小不足以表示XML实例,请尝试使用VARCHAR(MAX)。

 table_Name=$(printf "First_word\nSUMMARY_Details_V\nDETAIL_FACT_V")

答案 2 :(得分:0)

xulfi afridi,

您可以使用CAST(https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql#syntax)代替CONVERT,如下所示:

CAST(表达 AS data_type [(长度)]);

因此解决方案将是: 从EmployeeTable中选择* Where Cast(varchar,empname)=' @ combobox'

答案 3 :(得分:0)

代码应为:

Select * from EmployeeTable Where Cast(empname as varchar(max)) = @combobox