将存储过程的结果多次选择到单个结果集中

时间:2014-04-11 05:47:00

标签: sql sql-server stored-procedures

我有一个存储过程,可以选择两个随机的"提名"表中的类型。一对提名构成了我称之为" Battle"。每次战斗中的提名属于同一类别"。"。

create procedure sprocGetRandomBattle
as
select * from Nomination where NominationId in 
    (select top 2 NominationId from Nomination where IsActive = 1 and CategoryId in 
        (select CategoryId from Category where CategoryId in 
            (select top 1 CategoryId from Category where Active = 1 and CategoryId in 
                (select CategoryId from Nomination group by CategoryId having count(*) > 1)
            order by newid()) and OwnerId in 
        (select UserId from [User] where IsPrivate = 0))
    order by newid())
go

这个sproc做了一些事情:

  1. 获取随机有效类别ID
  2. 获取2个随机提名ID:a)属于我们随机选择的类别,b)是有效提名,c)由未标记为私有的用户拥有。
  3. 选择我们随机选择的2个提名ID的提名。
  4. 我这样做是作为一个sproc而不是使用LINQ,因为我需要撤回越来越大的结果集(随着时间的推移,随着数据的增长),以便在应用程序代码中进行随机选择。所以,我已经将该查询移到了这个sproc中。我希望运行此过程N次(在SQL中)并将其结果返回到一个大型集合中,这样我就可以避免从应用程序代码到SQl服务器进行多次调用。现在,我只需要在应用程序代码中循环调用sproc多次(N)。

    如何在SQL中多次执行此sproc N并将其作为一个大结果集返回?或者我可能只需要以某种方式修改sproc以获取参数并返回2 x N结果?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

create procedure sprocGetRandomBattle
@n int -- number of loops
as
declare @num int = 1;
declare @result table
    (
     -- input your column list
    )
while @num <=@n
begin   
insert into @result 
select * -- replace '*' with column list
from Nomination where NominationId in 
    (select top 2 NominationId from Nomination where IsActive = 1 and CategoryId in 
        (select CategoryId from Category where CategoryId in 
            (select top 1 CategoryId from Category where Active = 1 and CategoryId in 
                (select CategoryId from Nomination group by CategoryId having count(*) > 1)
            order by newid()) and OwnerId in 
        (select UserId from [User] where IsPrivate = 0))
    order by newid())
set @num = @num+1
end
select * from @result
go

我已经声明了一个输入参数,您需要传递&#39; n&#39;的值。然后该程序将运行&#39; n&#39;循环中的次数,并将结果填充到表变量中。完成所需的循环后,只需从表变量中选择所有结果即可。

相关问题