mysql 存储过程动态拼接

 CREATE PROCEDURE insertdata2 (IN table_name varchar(255))
  begin
      declare var_sql varchar(800);
      set var_sql = concat_ws(' ', 'select count(*) from  t_order where 1 = 1',table_name);
      set @sql = var_sql;
      PREPARE s1 from @sql; 
      EXECUTE s1; 
      deallocate prepare s1;
  end 

  call insertdata2(' ');

另一个例子

  CREATE DEFINER = `root`@`%` PROCEDURE `NewProc`(IN cid INT,IN offset       INT,IN num INT,IN where_name VARCHAR(500),out total INT)
  BEGIN  
  declare var_sql varchar(800);
  declare var_sqll varchar(1000);
  set total = @recordcount;
  CREATE TEMPORARY  table  tmpTable 
     (  
        `id`  int(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
   PRIMARY KEY (`id`)
 );  
   truncate TABLE tmpTable;  -- 使用前先清空临时表。  
             set var_sql = concat('SELECT count(*) INTO @recordcount from 
tmpTable where 1 = 1 ',where_name);
             set @sql = var_sql;
             PREPARE s1 from @sql; 
             EXECUTE s1; 
             deallocate prepare s1;
             SELECT @recordcount INTO total;
             set var_sqll = concat('SELECT * from tmpTable where 1 = 1 ', where_name, ' order by billingTime desc ','LIMIT ',offset,',',num);
             set @sql = var_sqll;
             PREPARE s1 from @sql; 
             EXECUTE s1; 
             deallocate prepare s1;
                
            
 DROP TABLE tmpTable;
 END;
mysql 存储过程动态拼接_第1张图片
image.png

你可能感兴趣的:(mysql 存储过程动态拼接)