I'd probably resort to a set-based loop.
DECLARE @ROWS INT = 0;
WHILE @ROWS = 0
BEGIN
WITH RandomWinners AS
(
SELECT TOP 5 *
FROM Ticket
ORDER BY NEWID()
)
SELECT *
INTO #RandomWinners
FROM RandomWinners;
IF EXISTS
(
SELECT sRace, sParty
FROM #RandomWinners
GROUP BY sRace, sParty
HAVING COUNT(CASE sRace WHEN 'W' THEN 1 END) >= 4 AND
COUNT(CASE sParty WHEN 'R' THEN 1 END) >= 4
)
SELECT *
FROM #RandomWinners;
SELECT @ROWS = @@ROWCOUNT;
DROP TABLE #RandomWinners;
END
Note that I have completely ignored political correctness w.r.t. supporting a lottery that seems to favor white republicans, on the basis that help on this forum is color blind.
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St