舊業務需求:一個客戶能夠被同一個公司下的不一樣用戶屢次新建。sql
新業務需求:一個客戶能夠被同一個公司下的用戶新建一次。oop
清洗舊業務遺留下來的數據,清洗規則:誰先建立客戶誰保留,後面建立的通通標記爲無用狀態。spa
DELIMITER $$ CREATE PROCEDURE deletechongfu() BEGIN DECLARE org_id INT(11); DECLARE count_num INT; DECLARE customer_code VARCHAR(32); DECLARE customer_id VARCHAR(255); -- 遍歷數據結束標誌 DECLARE done INT DEFAULT FALSE; DECLARE customerCursor CURSOR FOR SELECT t1.id,t1.code,t1.org_id,COUNT(*) AS COUNT FROM (SELECT t.id,t.org_id,t.name,t.code,tc.tuser_id,tc.create_time FROM credit.hd_tuser_customer tc INNER JOIN (SELECT t.code,t.name,t.org_id,t.id FROM credit.hd_customer_user t WHERE t.status = '1') t ON tc.customer_id = t.id WHERE tc.status = '1') t1 GROUP BY t1.code,t1.org_id HAVING COUNT >1; -- 將結束標誌綁定到遊標 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN customerCursor; -- 開始循環 read_loop: LOOP -- 提取遊標裏的數據,這裏只有一個,多個的話也同樣; FETCH customerCursor INTO customer_id,customer_code,org_id,count_num; SET @count_total = 0; SELECT customer_id INTO @customer_id; SELECT (count_num-1) INTO @count_total; PREPARE s1 FROM 'update credit.hd_tuser_customer set status = "0" where (customer_id,tuser_id) in (SELECT tt.customer_id,tt.tuser_id FROM (select t.customer_id,t.tuser_id from credit.hd_tuser_customer t where t.customer_id = ? and t.status = "1" order by t.create_time asc limit 0,?) tt)'; EXECUTE s1 USING @customer_id,@count_total; -- 聲明結束的時候 IF done THEN LEAVE read_loop; END IF; END LOOP; -- 關閉遊標 CLOSE customerCursor; END$$ DELIMITER ;
在寫存儲過程的途中,遇到如下問題:code
1:EXECUTE s1 USING @customer_id,@count_total 這裏只能是使用用戶變量。字符串
2:在編寫預處理語句的時候,用問號?來標記佔位符。要謹記該佔位符問號不能加引號或雙引號,即便與字符串鏈接。it
3:子查詢不支持limit條件限制,解決方法是在該處子查詢外面再包一層子查詢。class