2

When I run

SELECT SUM(CASE column1 WHEN 'sometext' THEN 1 ELSE 0 END)
FROM table1

I get the following error:

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

The column is datatype text so I tried the following but got the same error. Any ideas?

SELECT SUM(CASE column1 WHEN CAST('sometext' AS VARCHAR (40)) THEN 1 ELSE 0 END)
FROM table1
4

2 回答 2

0

this one works:

select sum(case when cast(column1 as varchar(max)) = 'sometext' then 1 else 0 end)
from table1

sql fiddle demo

于 2013-09-14T20:06:44.637 回答
0

You have to compare the column with the value, and if the column is other than varchar or ntext, the you have to convert the data type, otherwise type cast is not necessary, you can simply use,

select sum(case when column1 = 'sometext' then 1 else 0 end)
from table1

If column1 is other than string, then you can use

select sum(case when cast(column1 as varchar(max)) = 'sometext' then 1 else 0 end)
from table1

if column1 is ntext, then you can use

select sum(case when cast(column1 as nvarchar(max)) = N'sometext' then 1 else 0 end)
from table1

You can also check this answer here : http://techsharehub.blogspot.com/2013/09/compare-string-int-and-ntext-with.html

于 2013-09-16T01:05:03.893 回答