I use a stored procedure to randomly select 40 rows from a table with
BEGIN
INSERT INTO tblTestDetailSSM (IdIntrebare, IdUserTest)
SELECT TOP 40 ti.IdIntrebare AS IdIntrebare, @IdUserTest
FROM (SELECT TOP 100 * FROM tblIntrebare ORDER BY NEWID()) ti JOIN tblProcedura tp ON ti.IdProcedura = tp.IdProcedura WHERE tp.Specialitate = 'SSM' AND @CodTest IN (SELECT value FROM STRING_SPLIT(tp.CodTEST,','));
END
There are more than 200 items to pick from but the problem I have is that sometimes, it only picks 29 or less. What can I do to have exactly 40 every time?

Uday DodiyaPosted Oct 2, 2024, 4:47 AM
Hi,
The issue you're encountering is likely due to the JOIN and WHERE conditions in your query, which may reduce the result set below 40 rows. If there aren't enough matching rows in the tblIntrebare table (based on the join or filtering criteria like tp.Specialitate = 'SSM' and @CodTest IN (...)), you'll end up with fewer than 40 rows.
Steps to ensure you get exactly 40 rows every time:
Check filtering criteria: Ensure that there are at least 40 rows that meet the conditions in the JOIN and WHERE clause, especially the tp.Specialitate = 'SSM' and the @CodTest filtering. If there aren't 40 valid rows after applying the filters, you won't get 40 rows.
Use a fallback mechanism: You can add logic to handle cases where fewer than 40 rows are returned after applying the filters. This can involve picking more rows from the tblIntrebare table until you fill up to 40.
Here's an approach to ensure you always get 40 rows:
First, try to select 40 rows that meet your current filtering criteria. If fewer than 40 rows are returned, fill the remainder by selecting additional random rows from the same table, without applying the filter (or with relaxed conditions).
Key Points:
@TempTable: A temporary table is used to store the rows, ensuring that you can easily count and manage them before inserting into tblTestDetailSSM.This approach ensures that even if your filtering criteria reduce the available rows, you’ll still always insert 40 rows into tblTestDetailSSM.