mmcglynn
mmcglynn

Reputation: 7672

WHERE clause on SQL Server "Text" data type

Where [CastleType] is set as data type "text" in SQL Server and the query is:

SELECT *
FROM   [Village]
WHERE  [CastleType] = 'foo' 

I get the error:

The data types TEXT and VARCHAR are incompatible in the equal to operator.

Can I not query this data type with a WHERE clause?

Upvotes: 104

Views: 245485

Answers (7)

himan
himan

Reputation: 49

This works in MSSQL and MySQL:

SELECT *
FROM   Village
WHERE  CastleType LIKE '%foo%'; 

Upvotes: 0

Martin Smith
Martin Smith

Reputation: 453837

You can use LIKE instead of =. Without any wildcards this will have the same effect.

DECLARE @Village TABLE
        (CastleType TEXT)

INSERT INTO @Village
VALUES
  (
    'foo'
  )

SELECT *
FROM   @Village
WHERE  [CastleType] LIKE 'foo' 

text is deprecated. Changing to varchar(max) will be easier to work with.

Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

Upvotes: 113

SoggyBottomBoy
SoggyBottomBoy

Reputation: 71

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

Upvotes: 7

Emma Thapa
Emma Thapa

Reputation: 777

Please try this

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR, CastleType) = 'foo'

Upvotes: 28

Joe Stefanelli
Joe Stefanelli

Reputation: 135888

Another option would be:

SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0

Upvotes: 0

Will Marcouiller
Will Marcouiller

Reputation: 24142

That is not what the error message says. It says that you cannot use the = operator. Try for instance LIKE 'foo'.

Upvotes: 3

Donnie
Donnie

Reputation: 46943

You can't compare against text with the = operator, but instead must used one of the comparison functions listed here. Also note the large warning box at the top of the page, it's important.

Upvotes: 14

Related Questions