jeudi 13 octobre 2016

SQL Cursor to generate unique non sequencial PINS

I am trying to generate non sequential unique PINS for bunch of new employees. Here is how it should work: 1. A cursor should fetch all the new employees from table B 2. Generate new unique pins for each new employee 3. Check if the newly generated PIN already exists in Table A 4. If yes, repeat step 2 until we get unique PIN for all the new employees 5. Insert the new employee number and PINs into Table A

On table A the fields are PIN, Employee_Number, Date

I tried to use cursor to insert each new emp and his PIN one by one, so that it checks for uniqueness at each insert:

This only loops once and stops, can someone tell me what I am missing

 DECLARE 
    @EmpNo             VARCHAR(50), 
    @Pin               INT, 
    @today             DATETIME,
    @Upper             INT,
    @Lower             INT,
SET @Lower = 100000 ---- The lowest random number allowed
SET @Upper = 999999 ---- The highest random number allowed

DECLARE cur CURSOR FOR 

SELECT   
       Employee_Number, 
       (ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0))as PIN, 
       GETDATE()
FROM     TableB 
WHERE    Employee_Number NOT IN (SELECT Employee_Number FROM TableA)


OPEN cur
FETCH NEXT FROM cur INTO @EmpNo, @Pin, @Today

WHILE @@FETCH_STATUS=0

BEGIN    

         INSERT INTO TableA (PIN, Employee_Number, Date)
         SELECT @Pin, @EmpNo, @Today


FETCH NEXT FROM cur INTO @Pin, @EmpNo, @Today
END

CLOSE cur
DEALLOCATE cur




Aucun commentaire:

Enregistrer un commentaire