博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

sql去掉ntext类型的重复记录

Posted on 2011-02-18 16:39  孤独者  阅读(778)  评论(0编辑  收藏  举报

  在sql查询中,我们可以通过添加distinct关键字去掉重复记录,但是当表的字段中存在ntext或image类型的字段时,我们无法添加distinct关键字来过滤重复记录,查询会报错。这里有两种解决方案,一是在查询的时候将ntext类型强制转换为nvarchar的类型,并将大小设置为最大,避免丢失数据,这样就可以使用distinct关键字了;二是使用子查询来过滤查询结果。

create table Product

(

  id int identity(1,1) primary key,

  productName nvarchar(100),

  price decimal,

  description ntext

)

1.将ntext类型强制转换为nvarchar

select distinct id,productName,price,cast(description as nvarchar(4000)) as description

from Product

2.使用子查询过滤

select id,productName,price,description

from Product

where id in

(

  select max(id) from Product

  group by productName,price,description//除了主键不同,其他字段内容全部相同,对其他字段进行分组

)