I’m writing my first MySQL procedure. I try to generate a random number and update a value in a table with this number, but only if it doesn’t exists already (due to unique constraint). My procedure looks like this:
create procedure generaterc()
begin
declare _rc char;
declare _id int;
set _id = 1;
while _id < ((select count(*) from patient) - 1) do
begin
set _rc = cast(FLOOR(1000000000 + (RAND() * 8999999999)) AS char);
select _rc;
if not exists(select * from patient where patient.rc = _rc) then
update patient set rc=_rc where id=_id;
set _id=_id+1;
end if;
end;
end while;
end
I got this error when executing the procedure: Data truncation: Data too long for column ‘_rc’ at row 8. My rc column is varchar(255), but I guess this isn’t the core of the problem. Any suggestions?
Thank you very much.
Instead of
try:
Currently _rc can only hold a single character, which is not enough to store your number.
However, for your use case you may like to take a look at the uuid_short() function. It generates a large random number that is guaranteed to be unique (subject to some rules). This way you can replace your procedure with the single statement: