利用游标实现
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
(
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