This is my code:
if (!(string.IsNullOrEmpty(findIt)))
{
string query = @"select top (@Num) * from dbo.main where (Data = @FindIt) ";
// Data-> ntext
DataTable table = new DataTable();
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("@Num",limit);
myCommand.Parameters.Add(new SqlParameter("@FindIt", SqlDbType.NText)).Value = findIt;
myReader = myCommand.ExecuteReader(); // Run time error
myReader.Close();
myCon.Close();
}
}
}
Error message:
System.Data.SqlClient.SqlException: The data types ntext and ntext are incompatible in the equal to operator.
I don't know what it means and how to fix it
CodePudding user response:
The ntext
data type does not support equality comparisons. That data type has been deprecated for a long time and should not be used in a new database and should be changed in an existing database. Use nvarchar
instead if you possibly can. If you really must use ntext
in the database, you have three options in your query:
- Convert the database value to
nvarchar
and usenvarchar
for your parameter, then perform an equality comparison. - Perform a
LIKE
comparison. - Use the
PATINDEX
function to effectively do aLIKE
comparison and get the index of the match, which should be 1 for equality.
Note that a LIKE
comparison with no wildcards is effectively an equality comparison.