I have a table, Benefit
, where the policy number is to be generated randomly and should be unique of course. Below are my statements and query.
INSERT INTO Benefit([Company Name], [Policy #])
VALUES ('Assumption Life', RAND(100) * 100)
INSERT INTO Benefit([Company Name], [Policy #])
VALUES ('Aviva Canada', RAND(1) * 12)
INSERT INTO Benefit([Company Name], [Policy #])
VALUES ('Blue Cross' RAND(100) * 100)
INSERT INTO Benefit([Company Name], [Policy #])
VALUES ('Health & Dental Insurance' RAND(100) * 100)
I get the response:
Started executing query at Line 123
(1 row affected)
(1 row affected)
Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'UQ__Benefit__2E118E21CDDEB4E7'. Cannot insert duplicate key in object 'dbo.Benefit'. The duplicate key value is (71).Msg 2627, Level 14, State 1, Line 4
Violation of UNIQUE KEY constraint 'UQ__Benefit__2E118E21CDDEB4E7'. Cannot insert duplicate key in object 'dbo.Benefit'. The duplicate key value is (71).
The first two are successfully executed as the RAND()
functions are a bit different, but from 3rd it throws a duplication exception, since it is same as 1st record.
I tried RAND()
, and it always assigns 0. And from second row, throws same error.
Why it doesn't generate random number? Am I not clear with how to use RAND()
function?