Distinct function error in sql server

Learner 226 Reputation points
2021-08-16T14:23:35.5+00:00

Hello All,

I have a query and I need to get distinct of a field. Datatype is varchar.
But Its throwing below error.
I tried with cast but still the same error.

Code : distinct (convert(nvarchar(max),id))

Error :

The ntext data type cannot be selected as DISTINCT because it is not comparable.

Could anyone please help

SQL Server Other
{count} votes

2 answers

Sort by: Most helpful
  1. Guoxiong 8,206 Reputation points
    2021-08-16T15:24:39.36+00:00

    If the data type of the column is ntext, you need to convert it to nvarchar and then you are able to use DISTINCT. If the field id is ntext, your code should work

    SELECT DISTINCT(CONVERT(nvarchar(max), id))
    FROM YOUR_TABLE
    

    Or you can use CAST:

    SELECT DISTINCT(CAST(id AS nvarchar(max)))
    FROM YOUR_TABLE
    
    0 comments No comments

  2. YufeiShao-msft 7,146 Reputation points
    2021-08-17T01:57:59.26+00:00

    Hi @vissupangam-0394,

    The problem is caused by the fact that SQL Server’s ntext, text, and image data types have been declared obsolete.
    You can try to use the following code:

    select distinct (CAST (id AS nvarchar(max))) from table_name  
    

    the permanent and suggested solution is to permanently change the data type of the column(s) using the obsolete data type(s) into their corresponding accepted data types:

    ntext should become nvarchar(max)  
    text should become varchar(max)  
    image should become varbinary(max)  
    

    it can avoid losing valuable time with multiple CASTs and keep your query safe from performance issues.

    https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.