create table 表(a varchar(10),b int)
insert 表 select 'sfs',1
union all select 'sas',1
union all select 'sgs',1
union all select 'sts',1
union all select 'sfs',2
union all select 'sfs',2
union all select 'sfs',2
union all select 'sfs',2
union all select 'sfs',3
union all select 'sfs',3
union all select 'sfs',3
union all select 'sfs',3
union all select 'sfs',4
union all select 'sfs',4
union all select 'afs',4
union all select 'sfa',4
union all select 'sft',4
go
--查询,假设m=4
select id=identity(int,1,1),* into #t from 表
select * from #t a where id in(select top 4 id from #t where b=a.b)
drop table #t
go
假设你的
create procedure mypro(@m int,@n int)
as
begin
declare @sql varchar(8000)
declare @temp int
set @temp=0
set @sql=N''
while (@temp<@n)
begin
select @temp=@temp+1
select @sql=@sql+' select top '+cast(@m as varchar)+' * from a where bbb='+cast(@temp as varchar)+' Union'
end
select @sql=substring(@sql,1,len(@sql)-5);
exec(@sql)
end ;