mysql存储过程 将传入的参数用作为表名 执行时提示错误 Table 'asteriskcdrdb.tbname' doesn't exist 30
DELIMITER$$CREATEDEFINER=`root`@`localhost`PROCEDURE`NewProc`(intbnamevarchar(22))BEG...
DELIMITER $$
CREATE DEFINER = `root`@`localhost` PROCEDURE `NewProc`(in tbname varchar(22))
BEGIN
declare sExten char(10);
declare inCallnum int;
declare inCallsec int;
declare outCallnum int;
declare outCallsec int;
declare Extens char(10);
declare done int default 0;
declare cur3 cursor for SELECT DISTINCT (case when LENGTH(src)=3 then src else dst end ) as exten from tbname;
declare continue handler for sqlstate '02000' set done = 1;
open cur3;
repeat
fetch cur3 into Extens;
if not done THEN
SELECT ‘a’,'bbb';
#insert into outtbname (`extension`) values(hrtimes);
end if;
until done end repeat;
close cur3;
END$$
DELIMITER ; 展开
CREATE DEFINER = `root`@`localhost` PROCEDURE `NewProc`(in tbname varchar(22))
BEGIN
declare sExten char(10);
declare inCallnum int;
declare inCallsec int;
declare outCallnum int;
declare outCallsec int;
declare Extens char(10);
declare done int default 0;
declare cur3 cursor for SELECT DISTINCT (case when LENGTH(src)=3 then src else dst end ) as exten from tbname;
declare continue handler for sqlstate '02000' set done = 1;
open cur3;
repeat
fetch cur3 into Extens;
if not done THEN
SELECT ‘a’,'bbb';
#insert into outtbname (`extension`) values(hrtimes);
end if;
until done end repeat;
close cur3;
END$$
DELIMITER ; 展开
2个回答
展开全部
mysql 使用游标时,暂不支持动态sql语句的游标。
建议你先把拼接的sql语句 create table newtable select * from 表
然后在游标中用 from newtable,最后关闭游标后,再drop 这个newtable。
如:
declare stmt varchar(8000);
SET @SQL = Concat("create table newtable SELECT DISTINCT (case when LENGTH(src)=3 then src else dst end ) as exten from ", tbname );
prepare stmt from @SQL;
execute stmt;
deallocate prepare stmt;
declare cur3 cursor for SELECT exten from newtable;
建议你先把拼接的sql语句 create table newtable select * from 表
然后在游标中用 from newtable,最后关闭游标后,再drop 这个newtable。
如:
declare stmt varchar(8000);
SET @SQL = Concat("create table newtable SELECT DISTINCT (case when LENGTH(src)=3 then src else dst end ) as exten from ", tbname );
prepare stmt from @SQL;
execute stmt;
deallocate prepare stmt;
declare cur3 cursor for SELECT exten from newtable;
追问
我是需要将它select出来的结果再去查询其它的表,得出结果时就插入一表中。过程为
CREATE DEFINER = `root`@`localhost` PROCEDURE `NewProc`(in tbname varchar(22),in outtbname varchar(22));
open cur3;
repeat
fetch cur3 into Extens;
if not done THEN
insert into outtbname (`extension`) select src,'bbb' from outtbname where src=Extens;
end if;
追答
你这个 都不正确的。 mysql中 不可以直接使用 变量作为表名的。
你在 declare cur3 cursor for SELECT 。。。 from tbname ,你通过传入的参数作为 表名,但mysql在实际执行中 把 参数 tbname 作为实际存在的表名来执行查询的,故 tbname 是不存在的。
同理, 你 insert into 中的 outtbname 也是作为参数的,但 执行是 mysql当做表名的,而不是拼出来的 动态sql执行的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询