Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The data types text and varchar are incompatible in the equal to operator in C#

Tags:

c#

I am trying to access the data empname from the employeeTable, but the code I have written is giving me the following error:

The data types text and varchar are incompatible in the equal to operator.

Please suggest a solution

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();     } } 
like image 948
xulfi afridi Avatar asked Jan 11 '15 14:01

xulfi afridi


People also ask

Is varchar valid data type?

The VARCHAR data type accepts character strings, including Unicode, of a variable length is up to the maximum length specified in the data type declaration. A VARCHAR declaration must include a positive integer in parentheses to define the maximum allowable character string length.

What characters are allowed in varchar?

It can hold numbers, letters and special characters. Microsoft SQL Server 2008 (and above) can store up to 8000 characters as the maximum length of the string using varchar data type. SQL varchar usually holds 1 byte per character and 2 more bytes for the length information.

What is the difference between varchar and text in mysql?

Some Differences Between VARCHAR and TEXTThe VAR in VARCHAR means that you can set the max size to anything between 1 and 65,535. TEXT fields have a fixed max size of 65,535 characters. A VARCHAR can be part of an index whereas a TEXT field requires you to specify a prefix length, which can be part of an index.

What is Nvarchar vs varchar?

1. VARCHAR is a non-Unicode character data type with a maximum length of 8,000 characters, while NVARCHAR is a Unicode character data type with a maximum length of 4,000 characters. 2. VARCHAR literals are enclosed in single quotes, like 'John,' but NVARCHAR literals are prefixed with N also, for example, N'John.


2 Answers

You can't compare text to varchar, but as an answer to anyone in the future with this problem simply convert the text column to varchar for the query.

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

Always use parameters

SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = @comboBox"; 
like image 94
prospector Avatar answered Sep 18 '22 21:09

prospector


Try using VARCHAR(MAX) if the target string size is not big enough to represent the XML instance.

CONVERT(VARCHAR(MAX), empname) 
like image 43
live-love Avatar answered Sep 20 '22 21:09

live-love