1
mysql> select * from CT; 

| CID | MID | REPORT_QUERY   | 
| 1 | 1 | select * from emp;  | 
| 2 | 2 | select * from student; | 

2 rows in set (0.00 sec) 

我想在REPORT_QUERY列執行查詢。如何執行存儲在表列MySQL中的查詢?

DELIMITER // 
CREATE PROCEDURE TRYct() 
    BEGIN 
SET @str=(SELECT GROUP_CONCAT(REPORT_QUERY SEPARATOR ' ') FROM CT); 
PREPARE q from @str; 
EXECUTE q; 
    END // 
DELIMITER ; 

我用這個代碼,但它的工作原理,如果只有一個在我的表查詢。如果有兩個查詢比它給出一個錯誤。

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from student' at line 1 

問題在哪裏?幫我。

回答

0

據我瞭解你的問題是,你需要運行它們存儲在表列中SQL表查詢。

在這裏,您可以獲取查詢表格table column和mysqli的執行它們。

SQL查詢表的形象在這裏查詢存儲QUERY TABLE IMAGE

SQL EMPLOYEE TABLE [這是動態調用BY查詢表在執行期間]

employees table

PHP的SQL代碼:`

<?php 
    $link = new mysqli ('localhost','root','admin','demo'); 

    if($link->connect_error){ 
     die ("Connection Failed".$link->connect_error); 
    } 

    //YOU NEED THIS AS YOU NEED TO ACCESS THE COLUMN DATA IN TABLE 
    $sql = "SELECT * FROM querytable WHERE id=1"; 

    if($res = $link->query($sql)){ 
     //IF THE ROW EXISTS 
     if($res->num_rows > 0){ 
      while($row = $res->fetch_assoc()){ 

       $query = $row['report_query']; //HERE IS THE SQL QUERY STORED IN TABLE , WHICH IS STORED IN ANOTHER VARIABLE 
       $result = $link->query($query); // NOW EXECUTE THE QUERY 
       if($result->num_rows > 0){ 
      ?> 
        <table border="1" cellpadding="10"> 
         <tr> 
          <th>First Name</th> 
          <th>Last Name</th> 
         </tr> 
      <?php 
        while($rows = $result->fetch_assoc()){ 
         //DISPLAY RESULTS HERE 
      ?>   
         <tr> 
          <td><?php echo $rows['first_name'];?></td> 
          <td><?php echo $rows['lastname'];?></td> 
         </tr> 
      <?php 
        } 
      ?> 
        </table> 
     <?php 
       } 
      } 
     } 
    } 
    else 
    { 
     echo $link->error; 
    } 
?> 

`

1

您可以使用光標獲得每個REPORT_QUERYCT表,並執行使用預處理語句:

delimiter $$ 
drop procedure if exists run_queries$$ 
create procedure run_queries() 
begin 

    declare s_query varchar(255); 

    declare done bool default false; 
    declare c_queries cursor for  
     select REPORT_QUERY from CT; 
    declare continue handler for not found set done = true; 


    open c_queries; 
    read_loop: loop 

     fetch c_queries into s_query; 
     if done then 
      leave read_loop; 
     end if; 

     -- run the query 
     set @sql = s_query; 
     prepare stmt from @sql; 
     execute stmt; 
     deallocate prepare stmt; 
    end loop; 

end$$ 

創建過程後,可以爲波紋管撥打:

調用run_queries();

就是這樣。

+0

@伊萬Cachicatari .....謝謝主席先生 –

+0

@JaniHarsh你的歡迎,請考慮接受並給予好評我的答案:) –