您的位置:首页 > 其它

如何删除完全重复的列

2006-12-22 22:09 295 查看
利用游标实现

CREATE table userinfo
(
name char(10),
sex char(4),
phone char(10)
)

insert userinfo select 'aaa','男','12345' union all
select 'bbb','男','12345' union all
select 'aaa','男','12345' union all
select 'bbb','男','12345' union all
select 'aaa','男','12345' union all
select 'ccc','男','12345' union all
select 'aaa','男','1235'

--(1)定义
declare first cursor
for select count(*) as num ,name from userinfo
group by name

--(2)打开
open first

--(3)操作
declare @num int,@name varchar(10)
fetch next from first into @num,@name
while(@@fetch_status=0) --返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
--=0表示FETCH 语句成功
begin
declare second cursor for select * from userinfo where name=@name

open second

fetch next from second
while(@num >1)
begin
delete from userinfo where current of second
set @num=@num-1
fetch next from second
end
close second
deallocate second --删除游标引用
fetch next from first into @num,@name
end

close first
deallocate first

SELECT * FROM USERINFO
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: