mysql:creating cursor 在程序中动态地

hrirmatl  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(347)

下面我创建了一个过程,它使用了两个参数company\u name和sn\u f,
我想将表名作为参数传递给procedure,我想为其创建游标。

DELIMITER //
CREATE PROCEDURE transfer_t(IN company_name varchar(50), SN_f int)
BEGIN

DECLARE done BOOLEAN DEFAULT 0;
DECLARE dates_f date default null;
DECLARE high_f float default 0.0;
DECLARE low_f float default 0.0;
DECLARE open_f float default 0.0;
DECLARE close_f float default 0.0;
DECLARE volume_f int default 0;
DECLARE adj_close_f float default 0.0;

DECLARE Company_detail cursor for 
    select Date, high, low, open, close, volume, adj_close from company_name;
    Declare CONTINUE HANDLER FOR NOT FOUND SET done=1;
    OPEN Company_detail;
    REPEAT
        FETCH company_detail into dates_f, high_f, low_f, open_f, close_f, volume_f, adj_close_f;

        insert into historic_data(sn ,Date ,High ,low ,open ,close , volume , adj_close) values (SN_f,dates_f,high_f,low_f,open_f,close_f, volume_f, adj_close_f);

        until done END REPEAT;
        close company_detail;

END//
DELIMITER ;

上面的过程创建成功了,但是每当我这样调用它时,

call transfer_t('tcs_temp', 1);

它给出了以下错误

Error Code: 1146. Table 'test_schema.company_name' doesn't exist

请帮我解决这个问题。。。

cnjp1d6j

cnjp1d6j1#

您似乎希望将所有记录从作为参数给定的表名复制到另一个固定表中。我觉得这里不需要光标。sql是一种基于集合的语言,它是为在本地执行此类操作而构建的。您通常会使用 insert into ... select ... 语法。
另一方面,如果希望将表名用作变量,则需要使用动态sql—当前代码缺少该变量。
下面的代码应该是您想要的:

delimiter //

create procedure transfer_t(in p_company_name varchar(50), p_sn_f int)
begin
    set @p_sn_f = p_sn_f;
    set @sql = concat(
        'insert into historic_data(sn ,Date ,High ,low ,open ,close , volume , adj_close)',
        ' select ?, date, high, low, open, close, volume, adj_close from ', p_company_name
    );

    prepare stmt from @sql;
    execute stmt using @p_sn_f;
    deallocate prepare stmt;
end//

delimiter ;

相关问题