MS Sql Server 消除重复行 保留信息完整的一条 2011-11-26 13:19(QQ空间)
select company ,count(company) as coun into myls from mylist group by company having count(company)>1 --讲MyList重复的数据放到myls中
declare @id int
declare @company varchar(200)
declare @td table(id int,address nvarchar(200),linkman nvarchar(100),tel nvarchar(50),fax nvarchar(50),phone nvarchar(50),project nvarchar(200),product nvarchar(200),website nvarchar(100))
--临时表,将重复的几条放入其中,拿出数据完整的insert到listok中
declare @address nvarchar(200)
declare @linkman nvarchar(100)
declare @tel nvarchar(50)
declare @fax nvarchar(50)
declare @phone nvarchar(50)
declare @project nvarchar(200)
declare @product nvarchar(200)
declare @website nvarchar(100)
set @id=0
set @company=''
--注:3082488=select count(*) from myls+1
set @id=isnull((select top 1 id from myls where id>@id order by id),3082488)
while @id>=3082488
begin
set @company=(select company from myls where id=@id)
insert into @td(id,address,linkman,tel ,fax,phone,project,product,website)
select id,isnull(address,''),isnull(linkman,''),isnull(tel,'') ,isnull(fax,''),isnull(phone,''),cast(isnull(project,'') as nvarchar(200)),cast(isnull(product,'') as nvarchar(200)),isnull(website,'')
from mylist2 where company=@company
----取出完整的信息
set @address=isnull(select top 1 address from @td where address>''),'')
set @linkman=isnull(select top 1 linkman from @td where linkman>''),'')
set @tel=isnull(select top 1 tel from @td where tel>''),'')
set @fax=isnull(select top 1 fax from @td where fax>''),'')
set @phone=isnull(select top 1 phone from @td where phone>''),'')
set @project=isnull(select top 1 project from @td where project>''),'')
set @product=isnull(select top 1 product from @td where product>''),'')
set @website=isnull(select top 1 website from @td where website>''),'')
---- 讲完整的信息放入listok表
insert into listok(company,address,linkman,tel,fax.phone,project,product,website)
values(@company,@address,@linkman,@tel,@fax,@phone,@project,@product,@website)
delete from mylist2 where id in(select id from @td)
delete from @td
delete from myls where id=@id
set @id=0
set @id=isnull((select top 1 id from myls where id>@id order by id),3082488)
set @company=''
set @address=''
set @linkman=''
set @tel=''
set @fax=''
set @phone=''
set @project=''
set @product=''
set @website=''