27,581
社区成员
发帖
与我相关
我的任务
分享
create table t(id int,name varchar(10),type int)
insert into t select 1,'a',0
insert into t select 2,'a',0
insert into t select 3,'a',1
insert into t select 4,'a',0
insert into t select 5,'b',1
insert into t select 6,'b',0
insert into t select 7,'b',1
insert into t select 8,'b',1
go
declare @id int,@name varchar(10),@name1 varchar(10),@type int,@type1 int,@flag int
set @flag=0
declare cr cursor for
select id,name,type from t order by id
open cr
fetch next from cr into @id,@name1,@type1
fetch next from cr into @id,@name ,@type
while @@fetch_status=0
begin
if (@name=@name1)
begin
if (@flag=1) or (@type!=@type1)
begin
set @flag=1
delete t where id=@id
end
end
else
begin
select @name1=@name,@type1=@type,@flag=0
end
fetch next from cr into @id,@name ,@type
end
close cr
deallocate cr
select * from t
/*
id name type
----------- ---------- -----------
1 a 0
2 a 0
5 b 1
*/
go
drop table t
go
declare @t table(id int,name varchar(10),type int)
insert into @t select 1,'a',0
insert into @t select 2,'a',0
insert into @t select 3,'a',1
insert into @t select 4,'a',0
insert into @t select 5,'b',1
insert into @t select 6,'b',0
insert into @t select 7,'b',1
insert into @t select 8,'b',1
delete t from @t t where exists(select 1 from @t where id<t.id and name=t.name and type!=t.type)
select * from @t
/*
id name type
----------- ---------- -----------
1 a 0
2 a 0
5 b 1
*/