2012-05-09 61 views
0

我在寫我的第一個MySQL程序。我嘗試生成一個隨機數並使用此數字更新表中的值,但前提是它不存在(由於唯一約束)。我的過程是這樣的:MySQL程序隨機數產生

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 

我得到了執行程序時,這個錯誤:數據截斷:數據太長,在第8行的列「_RC」我的鋼筋混凝土柱爲varchar(255),但我想這不是問題的核心。有什麼建議麼?

非常感謝。

回答

0

而不是

declare _rc char; 

嘗試:

declare _rc varchar(255); 

目前_RC只能容納一個字符,這是不夠的,存儲你的電話號碼。

但是,對於您的用例,您可能需要查看uuid_short()函數。它會生成一個大的隨機數,保證它是唯一的(受一些規則約束)。這樣,您可以用單條語句替換您的程序:

update patient set rc = uuid_short(); 
+0

非常感謝!奇蹟般有效。我不能使用uuid_short()函數,因爲我需要_rc變量長達10個字符。 –