Error in in select data from table in SQL Server

2019-09-05 08:55发布

I use this code to select from a table in SQL Server 2008:

sqlcomm.CommandText = "select [objId] from [tablename] where href = @href"

The type of href in my table is ntext and I use this code to select:

 sqlcomm.Parameters.Add("@href", SqlDbType.NVarChar);
 sqlcomm.Parameters["@href"].Value = 'somestring';
 IDataReader reader = sqlcomm.ExecuteReader();

But it errors:

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

When I use SqlDbType.NText it have same error. I can't change type of href column in my table. When I use like @href it works, but I couldn't use LIKE because I want to exact match.

How can I solve my problem?

2条回答
我想做一个坏孩纸
2楼-- · 2019-09-05 09:30

The error is what it says. You cannot compare an NTEXT column with a NVarchar parameter.

sqlcomm.CommandText="select [objId] from [tablename] where cast(href as nvarchar(max))=@href"

ntext, text, and image (Transact-SQL) have been deprecated for a while now. Look to convert them to n/varchar(max) and varbinary(max) as soon as practicable.

查看更多
戒情不戒烟
3楼-- · 2019-09-05 09:48

You can't use ntext columns in a where clause in SQL. I'd suggest converting the column in the SQL statement if you are unable to change the existing column type e.g.CAST(href AS nvarchar(max)).

查看更多
登录 后发表回答