数据库mysql5.0
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `id` varchar(32) NOT NULL default '',
 
`name` varchar(20) default NULL,
 
PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create procedure test(in  tablename varchar(30))
begin
declare temp int;
select count(*) into temp  from tablename where id=1;
        if temp<1 then
insert into test values('1','ssss3333333334444444423');
else
update test set name='ssss66666' where id='1';
end if;
end 问题:这里有一个test表,我写了一个存储过程‘test’。存储过程中,参数tablename代表需要操作的表名。换句话说,
       就是要动态的传入表名。测试当中,出现了些问题。小弟入行不久。诚恳的请大家指教,帮助。十分的感谢。
       1、如果按照上面存储过程的写法,tablename这个地方报错。“jcms.tablename don't  exist”.说明tablename没有得到。
          但是,这个参数我已经确定传入了。
 
 后来,请教别人说要连成字符串。所以将存储过程修改如下。create procedure test(in  tablename varchar(30))
begin
declare temp int;
/*select count(*) into temp  from tablename where id=1;*/
DECLARE stmt varchar(2000);
set @sqlstr=concat('select count(*)  into  temp  from',tablename,' where id= 1');
prepare stmt from @sqlstr;
execute stmt ;
        if temp<1 then
insert into tablename values('1','ssss3333333334444444423');
else
update tablename set name='ssss66666' where id='1';
end if;
end结果又出现下面的问题:
1、执行存储过程,说变量temp没有定义。昨晚试了很多方式,都不可以的。所以在此请教了。请朋友们赐教。

解决方案 »

  1.   

    DELIMITER $$DROP PROCEDURE IF EXISTS `test`.`test`$$CREATE DEFINER=`root`@`localhost` PROCEDURE `TEST`(in  tablename varchar(30))
    begin
    set @sqlstr=concat('select count(*)  into  @temp  from ',tablename,' where id= 1');
    prepare stmt from @sqlstr;
    execute stmt ;
          if @temp <1 then
    set @sqlstr=concat(
    'insert into ',tablename,'values(\'1\',\'ssss3333333334444444423\'');
    prepare stmt from @sqlstr;
    execute stmt ;
    select @sqlstr;
    else
    set @sqlstr=concat(
    'update ',tablename,' set name=\'ssss66666\' where id=\'1\'');
    select @sqlstr;
    prepare stmt from @sqlstr;
    execute stmt ;
    end if;
    end$$DELIMITER ;