11,848
社区成员
发帖
与我相关
我的任务
分享
if object_id('tempdb..#t1') is not null drop table #t1
create table #t1(leibie varchar(100),zongshu int,del_shu int)
insert into #t1
select 'a',5,3 union all
select 'b',6,3
if object_id('tempdb..#t2') is not null drop table #t2
create table #t2(leibie varchar(100),[order] int)
insert into #t2
select 'a',1 union all
select 'a',2 union all
select 'a',3 union all
select 'a',4 union all
select 'a',5 union all
select 'b',1 union all
select 'b',2 union all
select 'b',3 union all
select 'b',4 union all
select 'b',5 union all
select 'b',6
declare @s nvarchar(max)
/*
--多次删除
select @s=isnull(@s+';','')+'delete t from (select *,row_number()over(partition by leibie order by [order] desc) as seq from #t2) as t where t.leibie='''+leibie+''' and [seq]<= '+ltrim(del_shu)+char(13) from #t1
--print @s
--exec(@s)
*/
--一次删除
set @s ='delete t from (select *,row_number()over(partition by leibie order by [order] desc) as seq from #t2) as t where [seq]<=case '
select @s=@s+' when leibie='''+leibie + ''' then ' +ltrim(del_shu) from #t1
set @s= @s+' end '
exec(@s)
select * from #t2