while或for循环逻辑

时间:2016-07-18 06:51:15

标签: sql plsql

我正在尝试为以下要求编写逻辑但我无法提出解决方案。

  1. 对于项目I1,光标C1将具有fetch file_qty和table_qty,其中file_qty对于所有记录都是相同的。
  2. 2.取决于此数据提取插入应该发生在表t2中。

    例如: 对于项目I1光标C1获取4行

    file_qty=-12, table_qty=5
    file_qty=-12, table_qty=6
    file_qty=-12, table_qty=5
    file_qty=-12, table_qty=4
    

    然后将数据插入t2,直到file_qty变为零。即

    select sum(table_qty+file_qty) from dual;
    
    for row1 : 5-12 =-7 = insert data into t2 with qty=5
    for row2 : 6-7 = -1 = insert into t2 with qty=6
    for row3 : 5-1 = 4 = insert into t2 with qty=1
    for row4 no data should be inserted in t2 since file_qty has become zero. i.e 5+6+1 = 12 = file_qty
    

    如何在plsql循环中实现这个逻辑?

1 个答案:

答案 0 :(得分:1)

以下是您可以编写程序的示例。有些部分缺失,因为您没有详细描述它们,但应该很容易完成它们(参见注释):

DECLARE

    lc_file_qty NUMBER := -12;

BEGIN

    FOR c1 IN (
        SELECT table_qty
        FROM t1
        WHERE file_qty = lc_file_qty
        ORDER BY ??? -- Not clear if we need any ordering criteria?
    ) LOOP

        lc_file_qty := lc_file_qty + c1.table_qty;

        IF lc_file_qty >= 0 THEN EXIT; END IF; -- Break the loop

        INSERT INTO t2(???) VALUES (???); -- Insert into t2 table (must complete!)

    END LOOP;

    COMMIT;

END;