DECLARE
CURSOR cursor IS SELECT SHIP_ID, DATE_ARRIVE, QTY_EXPECTED, DESCRIPTION, QTY_HAND, ITEM_RATE, (QTY_EXPECTED * ITEM_RATE), ((QTY_EXPECTED * ITEM_RATE) + (QTY_HAND * ITEM_RATE)),((QTY_EXPECTED * ITEM_RATE) + (QTY_HAND * ITEM_RATE))
FROM SHIPPINGTABLE;
S_SHIPID SHIPPINGTABLE.SHIP_ID%TYPE;
S_DATEARRIVE SHIPPINGTABLE.DATE_ARRIVE%TYPE;
S_QTYEXPECTED SHIPPINGTABLE.QTY_EXPECTED%TYPE;
S_DESCRIPTION SHIPPINGTABLE.DESCRIPTION%TYPE;
S_QTYHAND SHIPPINGTABLE.QTY_HAND%TYPE;
S_ITEMRATE SHIPPINGTABLE.ITEM_RATE%TYPE;
S_SHIPMENTVALUE NUMBER(10);
S_TOTALVALUE NUMBER(10);
S_GRANDTOTAL NUMBER(10) := 0;
BEGIN
OPEN cursor;
LOOP
FETCH CURSOR INTO S_SHIPID, S_DATEARRIVE, S_QTYEXPECTED, S_DESCRIPTION, S_QTYHAND, S_ITEMRATE, S_SHIPMENTVALUE, S_TOTALVALUE, S_GRANDTOTAL;
EXIT WHEN cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Shipment ' || S_SHIPID || ' is expected to arrive on '|| S_DATEARRIVE);
DBMS_OUTPUT.PUT_LINE('Description: ' || S_DESCRIPTION);
DBMS_OUTPUT.PUT_LINE('Shipment value: ' || S_SHIPMENTVALUE);
DBMS_OUTPUT.PUT_LINE('Quantity on hand: ' || S_QTYHAND);
DBMS_OUTPUT.PUT_LINE('Total product value: ' || S_TOTALVALUE);
DBMS_OUTPUT.PUT_LINE(CHR(10));
S_GRANDTOTAL := S_TOTALVALUE + S_GRANDTOTAL;
END LOOP;
DBMS_OUTPUT.PUT_LINE(S_GRANDTOTAL);
CLOSE cursor;
END;
/
我正在计算总计。现在输出如下
Shipment 211 is expected to arrive on 15-Nov-07
Description: Season Tents
Shipment value: 12500.
Quantity on hand: 3
Total product value: 14000
每个项目都是正确的。它还输出S_GRANDTOTAL,但它只将最后一项添加到自身,因此它不会添加前一项的总计。我知道在java中你可以做类似
的事情 variable += variable
有没有办法在sql中执行此操作?
答案 0 :(得分:1)
与Java相同的PL / SQL [variable1 + = variable2]是[variable1:= variable1 + variable2]。所以乍一看,你的[S_GRANDTOTAL:= S_TOTALVALUE + S_GRANDTOTAL]看起来是正确的。但是,在SQL语句中,GRANDTOTAL的源派生与TOTAL_VALUE [((QTY_EXPECTED * ITEM_RATE)+(QTY_HAND * ITEM_RATE))]的源派生相同。从SQL语句中删除最后一个字段定义,从游标提取语句中删除[[INTO] S_GRANDTOTAL]元素,我认为您的代码将按预期工作; TOTAL_VALUE将从零到最终累积地添加到S_GRAND_TOTAL变量,并显示在报告的末尾。
如果您在SQL语句中为派生字段设置别名,那将会很有帮助,例如:SELECT SHIP_ID,DATE_ARRIVE,QTY_EXPECTED,DESCRIPTION,QTY_HAND,ITEM_RATE,(QTY_EXPECTED * ITEM_RATE) AS SHIPMENT_VALUE ,( (QTY_EXPECTED * ITEM_RATE)+(QTY_HAND * ITEM_RATE)) AS TOTAL_VALUE
像这样的PL / SQL游标循环是不可扩展的,也就是说,如果表包含数百万或数十亿行和/或系统上存在高活动,它将使您的系统陷入困境。 /> 出于这个原因,我建议在前端使用报告工具,在后端使用单个SQL(不是PL / SQL游标循环)语句。让工具执行多级细节,聚合和汇总。