MySQL:如何在表中插入新行时动态调用存储过程

时间:2017-06-25 09:42:56

标签: mysql sql

我有一个查询,在表中插入新行时动态地将行转换为列。但是,每次在表中插入新行时,我都需要调用存储过程来显示输出call bian_test_db.new_procedure();。如何在不调用过程的情况下自动显示新的插入数据。

CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`()
BEGIN
SET SESSION group_concat_max_len = 1000000;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS ',
      itemname
    )
  ) INTO @sql
FROM
  bian_test_db.history;
SET @sql = CONCAT('CREATE OR REPLACE view testing as SELECT user_id, ', @sql, ' 
                  FROM bian_test_db.history 
                   GROUP BY user_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

2 个答案:

答案 0 :(得分:1)

首先创建以下程序

   
<ul>
  <li>
    <div class="pic">
      <img src="https://cdn.pixabay.com/photo/2017/05/14/14/24/grass-2312139__340.jpg">
    </div>
    <div class="text">
A longer text which should wrap to multiple lines.
    </div>
  </li>
  <li>
    <div class="pic">
      <img src="https://cdn.pixabay.com/photo/2017/06/14/23/15/soap-bubble-2403673__340.jpg">
    </div>
    <div class="text">
A longer text which should wrap to multiple lines.
    </div>
  </li>  
  <li>
    <div class="pic">
      <img src="https://cdn.pixabay.com/photo/2017/05/04/19/32/sculpture-2284945__340.jpg">
    </div>
    <div class="text">
A longer text which should wrap to multiple lines.
    </div>
  </li>  
</ul>

然后创建下面的触发器,从上面调用Procedure。

CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`()
BEGIN
SET SESSION group_concat_max_len = 1000000;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS ',
      itemname
    )
  ) INTO @sql
FROM
  bian_test_db.history;
SET @sql = CONCAT('CREATE OR REPLACE view testing as SELECT user_id, ', @sql, ' 
                  FROM bian_test_db.history 
                   GROUP BY user_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

希望这会对你有所帮助。

答案 1 :(得分:0)

您可以使用触发器

CREATE TRIGGER your_trigger_name AFTER INSERT ON your_table 
   FOR EACH ROW 
   BEGIN 
           .... your code 
   END

请参阅https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.htmlhttps://dev.mysql.com/doc/refman/5.7/en/create-trigger.html