2014-12-06 88 views
0

我是新來的存儲過程。我有客戶表,它有像customerid,customerName,companyName這樣的列。我正在創建新列email_address。哪個工作正常。現在我試圖使用商店程序爲每個客戶添加電子郵件地址值。我在電子郵件地址中輸入了customername和companyName。但不知何故它沒有更新。這裏是我的代碼變量聲明無法更新表中的單列值

CREATE PROCEDURE test() 
BEGIN 
DECLARE variable 
DECLARE CURSOR FOR 
SELECT CustomerID, CompanyName, ContactName, EmailAddress 
FROM customers; 

DECLARE EXIT HANDLER 

OPEN cursor_name; 

WHILE row_not_found = FALSE 
    DO  
      FETCH customers_cursor 
      INTO customer_id_var, company_name_var, contact_name_var, email_id_var; 

      SET email_part1 = REPLACE (contact_name_var, ' ', ''); 
      SET email_part2 = substring_index(company_name_var, ' ', 1);  

      update customers 
      SET EmailAddress = CONCAT(email_part1, '@', email_part2, '.com') 
      WHERE CustomerID = customer_id_var; 

      SET update_count = update_count + 1; 


    END WHILE; 

CLOSE cursor_name;  

    SELECT * FROM customers; 

END// 

DELIMITER ; 

CALL test(); 

回答

1

後,您不需要爲這個光標:

update customers 
    set EmailAddress = CONCAT(REPLACE(contact_name_var, ' ', ''), '@', 
           substring_index(company_name_var, ' ', 1), '.com'); 

這比使用遊標,它應該有更好的表現要簡單得多。

(我不打算評論創建電子郵件地址的實際邏輯,除非說在很多情況下它很可能失敗。)