日期:2014-05-17  浏览次数:21026 次

如何编写一个循环查询表中记录并把结果保存在临时表中
有很多表
table1
id month fee  
 1 201207 12
 1 201207 -6
table2
id month fee
2 201207 3
2 201207 -2
table3
id month fee
3 201207 4
3 201207 -1
  .
  .
  .
  .
比如说有五个表 如何用循环语句编写fee<0的记录保存到临时表中
各位大侠 帮忙解决下吧 谢谢

------解决方案--------------------
--这个例子是三个表的,改动一下参数就行---
CREATE TABLE fee1(ID NUMBER ,months VARCHAR2(20),fee NUMBER);
CREATE TABLE fee2(ID NUMBER ,months VARCHAR2(20),fee NUMBER);
CREATE TABLE fee3(ID NUMBER ,months VARCHAR2(20),fee NUMBER);

INSERT INTO fee1 VALUES(1,'201207',12);
INSERT INTO fee1 VALUES(1,'201207',-6);
INSERT INTO fee2 VALUES(2,'201207',3);
INSERT INTO fee2 VALUES(2,'201207',-2);
INSERT INTO fee3 VALUES(3,'201207',4);
INSERT INTO fee3 VALUES(3,'201207',-1);
COMMIT;

CREATE TABLE fee_temp(ID NUMBER ,months VARCHAR2(20),fee NUMBER);


DECLARE
v_Sql VARCHAR2(1000);
BEGIN
v_Sql := 'INSERT INTO fee_temp SELECT * FROM fee';
FOR i IN 1 .. 3 LOOP
v_Sql := v_Sql || i || ' where fee<0';
EXECUTE IMMEDIATE v_Sql;
v_Sql := 'INSERT INTO fee_temp SELECT * FROM fee';
END LOOP;
END;

------解决方案--------------------
在三樓的基礎上稍改下不就好了


SQL code

--v_cur你看下你的表屬於什麼倏件,加入一次性取出就可以了
declare 
    v_sql varchar(4000);
    cursor v_cur is select table_name from user_tables where table_name like 'FEE%'; 
begin
    for v in v_cur
    loop
        v_sql := 'insert into fee_temp select * from '||v.table_name||' where fee<0';
        execute immediate v_sql;
    end loop;
    commit;
end;
/