2013-03-13 23 views
0

我有一些觸發器將通話記錄作爲blob保存到數據庫中。我想添加一些額外的功能,每次觸發時都會執行,並有助於將數據庫保留在一定的大小限制內:功能必須執行以下操作:while循環只使用mysql查詢語言

必須計算blob文件的總和。當它大於給定值時,從表中刪除最早的記錄。

我不知道我在做什麼錯。請看一看

WHILE ((select sum(OCTET_LENGTH(recordfile))/1000000 from callrecords)>0,1) 
DO 
BEGIN 
DELETE FROM callrecords ORDER BY id ASC LIMIT 1; 
END; 
END WHILE; 

下面是數據庫看起來像事先

-- ---------------------------- 
-- Table structure for `callrecords` 
-- ---------------------------- 
CREATE TABLE `callrecords` (
    `id` bigint(20) NOT NULL AUTO_INCREMENT, 
    `uid` varchar(150) COLLATE utf8_unicode_ci NOT NULL, 
    `callerid` int(11) NOT NULL, 
    `extension` int(11) NOT NULL, 
    `calldate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    `recordfile` longblob, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM AUTO_INCREMENT=350 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

THX。

+0

那麼,什麼happpens?你的觸發器是否運行?它是否刪除記錄?你有錯誤嗎?什麼是錯誤? – Jocelyn 2013-03-13 16:48:35

回答

0

您應該將blob文件大小選擇到循環外的變量中,然後通過在每次刪除後重新運行select來更新變量。根據您最初的嘗試

代碼示例:

declare v_size int; 
... 
-- initialize the variable 
select sum(OCTET_LENGTH(recordfile)) 
into v_size 
from callrecords; 

while (v_size > 1000000) 
do 
    DELETE FROM callrecords ORDER BY id ASC LIMIT 1; 

    -- update the variable 
    select sum(OCTET_LENGTH(recordfile)) 
    into v_size 
    from callrecords; 

end while;