2012-10-04 53 views
7

Tôi muốn xuất dữ liệu từ mọi bảng có chứa cột first_name. Tôi đặt cùng thủ tục sau đây, nhưng trong vòng lặp của tôi, mysql diễn giải tên bảng theo nghĩa đen thay vì đánh giá biến số table_name. Sửa chữa là gì?Vòng lặp MySQL qua các bảng

delimiter // 

drop procedure if exists hunt // 
create procedure hunt() 
begin 
    DECLARE done int default false; 
    DECLARE table_name CHAR(255); 

    DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = "wholesale_production" and COLUMN_NAME LIKE "%first%" ; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
    open cur1; 

    myloop: loop 
     fetch cur1 into table_name; 
     if done then 
      leave myloop; 
     end if; 
     select * from `wholesale_production`.table_name where created_at >= '2012-10-01'; 
    end loop; 

    close cur1; 
end // 

delimiter ; 

call hunt(); 

Trả lời

9

Hãy thử điều này:

delimiter // 

drop procedure if exists hunt // 
create procedure hunt() 
begin 
    DECLARE done int default false; 
    DECLARE table_name CHAR(255); 

    DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = "wholesale_production" and COLUMN_NAME LIKE "%first%" ; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
    open cur1; 

    myloop: loop 
     fetch cur1 into table_name; 
     if done then 
      leave myloop; 
     end if; 
     set @sql = CONCAT('select * from `wholesale_production`.', table_name, ' where created_at >= '2012-10-01'); 
     prepare stmt from @sql; 
     execute stmt; 
     drop prepare stmt; 
    end loop; 

    close cur1; 
end // 

delimiter ; 

call hunt(); 
+1

Tôi gặp vấn đề tương tự. Nếu tôi không quan tâm đến việc lọc tên bảng thành 'LIKE '% first%'', tôi có thể sử dụng 'SHOW TABLES' thay vì' SELECT TABLE_NAME ... 'không? – Kal

+1

table_name là tên dành riêng. nên được đổi thành tên khác. –

-1

trong cur1 bạn đang sử dụng TABLE_NAME có thử sử dụng một tên thật của bảng

+1

Nhưng bảng không được biết, anh ấy nhận được tên bảng từ INFORMATION_SCHEMA. – Barmar

0

một chút chỉnh sửa ở trên để itertate ahtoug tất cả các bảng và chọn chúng.

delimiter // 
drop procedure if exists hunt // 
create procedure hunt() 
begin 
    DECLARE done int default false; 
    DECLARE table_name CHAR(255); 

    DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES 
        WHERE table_schema ='mbu4u'; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
    open cur1; 
     myloop: loop 
     fetch cur1 into table_name; 
     if done then 
      leave myloop; 
     end if; 
     set @sql = CONCAT('select * from `mbu4u`.',table_name); 
     prepare stmt from @sql; 
     execute stmt; 
     drop prepare stmt; 
    end loop; 

    close cur1; 
end // 

delimiter // 
0

table_name là một mã thông báo dành riêng sử dụng tên biến khác trong "DECLARE table_name CHAR (255);"

Các vấn đề liên quan