表名作为for循环

时间:2017-05-03 11:52:23

标签: sql stored-procedures db2

我想将以下脚本从DB2的FOR循环的静态sql语句转换为动态的。具体地从过程参数中获取tablename并在FOR DO循环的SQL语句中使用它。

起点是这个脚本:

CREATE PROCEDURE P()
LANGUAGE SQL
BEGIN ATOMIC
DECLARE fullname CHAR(40);

FOR v AS cur1 CURSOR FOR 
            SELECT firstnme, midinit, lastname FROM employee
DO 
  SET fullname = v.lastname || ',' || v.firstnme 
                 ||' ' || v.midinit;
  INSERT INTO tnames VALUES (fullname);
END FOR;
END

我想做这样的事情:

CREATE PROCEDURE P(IN TABLENAME VARCHAR(128) DEFAULT 'TABLE1')
LANGUAGE SQL
BEGIN ATOMIC
DECLARE fullname CHAR(40);

FOR v AS cur1 CURSOR FOR 
            SELECT firstnme, midinit, lastname FROM TABLENAME 
DO 
  SET fullname = v.lastname || ',' || v.firstnme 
                 ||' ' || v.midinit;
  INSERT INTO tnames VALUES (fullname);
END FOR;
END

有办法做到这一点吗?我已经尝试了STATEMENT,但我无法使其与FOR LOOP一起使用。

1 个答案:

答案 0 :(得分:0)

我设法在没有FOR LOOP的情况下使用此方法让它工作:

CREATE OR REPLACE  PROCEDURE P(IN TABLENAME VARCHAR(100) DEFAULT 'TABLE1')
 LANGUAGE SQL
 BEGIN 
    DECLARE fname VARCHAR(100);
    DECLARE mdinit VARCHAR(100);
    DECLARE lname VARCHAR(100);
    DECLARE dumy VARCHAR(100) DEFAULT 'POP';
    DECLARE stmt STATEMENT;
    DECLARE cur1 CURSOR FOR stmt;

    SET text = 'SELECT firstnme, midinit, lastname FROM ' || TABLENAME;
    PREPARE stmt FROM text; 
    OPEN cur1;
    fetch_loop:
        LOOP FETCH cur1 INTO fname,mdinit,lname; 
        EXECUTE IMMEDIATE 'update '|| TABLENAME || ' set midinit=' || dumy || ' where firstname = ' || fname; 
        END LOOP fetch_loop;
    CLOSE cur1;
END

但仍然没有FOR LOOP

的解决方案