2014-04-11 167 views
0

我有一個存儲過程從表中選擇兩個隨機「提名」類型。一對提名構成了我所說的「戰鬥」。每場戰鬥中的提名都屬於同一個「類別」。將存儲過程的結果多次選擇到一個結果集中

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 

此存儲過程做了幾件事情:

  1. 隨機獲得一個活躍的類別ID
  2. 把那2個隨機提名編號:A)屬於該類別我們只是隨機選擇,b)是積極提名,以及c)由未被標記爲私人的用戶擁有。
  3. 爲我們隨機選擇的2個提名ID選擇提名。

我這樣做是作爲一個sproc而不是使用LINQ的,因爲我需要拉回越來越大的結果集(隨着數據量的增長),以便在應用程序代碼中進行隨機選擇。所以,我已經把這個查詢移入了這個存儲過程。我想運行此過程N次(在SQL中)並將其結果返回到一個大集合中,以便我可以避免從應用程序代碼向SQl服務器進行多次調用。現在,我只需按需要多次調用應用代碼中的sproc循環(N)。

如何在SQL中多次執行此存儲過程N並將其作爲一個大型結果集返回?或者,也許我只需要修改sproc以獲取參數並返回2 x N個結果?任何幫助,將不勝感激。

回答

1

試試這個:

create procedure sprocGetRandomBattle 
@n int -- number of loops 
as 
declare @num int = 1; 
declare @result table 
    (
    -- input your column list 
    ) 
while @num <[email protected] 
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 

我已經宣佈的輸入參數,對此您將需要通過「n」的值。然後該過程將在循環中運行n次,並將結果填充到表變量中。完成所需的循環後,只需從表變量中選擇所有結果即可。

+0

太棒了!謝謝! – NovaJoe

+0

是的,我可以證實這是我正在尋找的。按預期工作。 – NovaJoe

相關問題