1、动态sql, 即动态参数:
在存储过程中,想要直接用表名变量做参数,动态执行sql,不能直接写
<P>create procedure ( $tableName char(20) ) <P>BEGIN <P>select * from tableName; <P>END </P>
mysql 不支持表名作为变量,这样会直接将变量名“tableName”作为表名去查询,解决的方法是:
<P>BEGIN <P>SET @sql = concat('select * from ', $tableName); <P>PREPARE stmt1 FROM @sql; <P>EXECUTE stmt1; <P>DEALLOCATE PREPARE stmt1; <P>END; </P>
2 得到动态sql, select查询的结果:
可以直接 在sql 语句中 得到, "select * into @var" 就行了,后边就可以直接运用该变量了。
例子:
<P>SET @sql = concat('select max(id) into @max_id from ', $tableName); <P>PREPARE stmt1 FROM @sql; <P>EXECUTE stmt1; <P>DEALLOCATE PREPARE stmt1; </P>此时,@max_id 就保存了查询结果。
附上一个例子:
<P>DROP PROCEDURE IF EXISTS get_service_id;<BR>DELIMITER $<BR>CREATE PROCEDURE get_service_id<BR>(<BR>IN $tableName varchar(25),<BR>IN $beginDate varchar(25)<BR>) <P>SET @sql = concat('select id into @mainId from ', $tableName , ' where date_time>=\"', $beginDate, '\" order by date_time limit 1');<BR>PREPARE stmt1 FROM @sql;<BR>EXECUTE stmt1;<BR>DEALLOCATE PREPARE stmt1; <P>END;<BR>$<BR>DELIMITER ; </P>