Edited: Suspect procedure timeout to be the culprit, so seeking more efficient way to proceed. thanks
I'm struggling with a routine that as far as I can see should work but isn't.
The stored procedure should generate x-number of random strings (8 chars) and then insert them into a table. A check for uniqueness is carried out also. Batch size for code generation is 250k codes.
My issue is that not all requested codes are generated all of the time, sometimes the generated batch size is smaller and I can't figure out why? Sometime it runs the full 250k codes are generated, sometimes it only generate 240k ?? The whole routine takes about 30 seconds to complete.
Thanks muchly in advance
DECLARE @i int = 1, @chars char(32), @result char(8), @cntR int, @rfQty int = 0
SET @chars = N'23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
WHILE (@i <= 250000)
BEGIN
/* generate code */
SET @cntR = 0;
SET @result = SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
+ SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1);
/* is unique ? */
SELECT @cntR = COUNT(rfcode)
FROM tblCodes
WHERE rfCode = @result;
/* insert result if unique */
IF @cntR = 0
BEGIN
INSERT INTO tblCodes (rfCode)
VALUES (@result);
SET @i = @i + 1;
END
END