如今遇到一個問題,MySQL數據庫中有個images字段,用於存取文章中全部圖片地址,有些地址是基於服務器的絕對路徑,例如/watercms/upload/image/20160204/1454573950573007716.jpg,/watercms/upload/image/20160204/1454573944458029036.jpg,若是是App訪問的話,這些圖片就讀取不出來了,所以經過存儲過程來把字段中的圖片路徑,修改成帶網絡地址的路徑。
sql
思路:先將images字段,經過間隔符split成單個的圖片地址,而後判斷當前地址是否以http開頭,若是不是,則加上http,而後把單個的圖片地址再拼接起來,update到數據庫中。數據庫
DROP FUNCTION IF EXISTS func_get_split_string_total; CREATE FUNCTION func_get_split_string_total( f_string TEXT,f_delimiter varchar(5) ) RETURNS int(11) BEGIN RETURN 1 + (length(f_string) - length(replace(f_string,f_delimiter,''))); END
定義方法,計算字符串經過,分隔符功能分隔成幾段服務器
DROP FUNCTION IF EXISTS func_split_str; CREATE FUNCTION func_split_str( x VARCHAR(5000), delim VARCHAR(12), pos INT )RETURNS VARCHAR(500) BEGIN RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, ''); END
定義方法取得經過分隔符分割成段的第幾段字符。網絡
CREATE PROCEDURE `pro_update_knowledge_images`() BEGIN DECLARE done INT DEFAULT FALSE; DECLARE kid INT; DECLARE images VARCHAR(5000); DECLARE new_img VARCHAR(200); DECLARE new_imgs VARCHAR(5000); DECLARE image_count INT; DECLARE i_index INT; DECLARE k_images_cursor CURSOR FOR SELECT k.id,k.images FROM ww_article_knowledge k WHERE k.`status` = 1 AND k.images IS NOT NULL AND k.images!=''; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN k_images_cursor; read_loop:LOOP FETCH k_images_cursor INTO kid,images; IF done THEN LEAVE read_loop; END IF; SET image_count = func_get_split_string_total(images,','); SET i_index = 1; SET new_imgs = ''; WHILE i_index<=image_count DO SET new_img = func_split_str(images,',',i_index); IF new_img NOT LIKE 'http%' THEN SET new_img = CONCAT('http://uhome.haier.net:8280',new_img); END IF; IF i_index > 1 THEN SET new_imgs = CONCAT(new_imgs,',',new_img); ELSE SET new_imgs = new_img; END IF; SET i_index = i_index + 1; END WHILE; UPDATE ww_article_knowledge SET images=new_imgs WHERE id=kid; COMMIT; END LOOP; CLOSE k_images_cursor; END
利用遊標,對錶的images字段進行處理。oop