我正在尝试进行两次聚合并在存储过程中返回值。 这是我的表:
CREATE TABLE T_TEST (TEST NUMERIC(10) ) ;
INSERT INTO T_TEST VALUES (1) ;
INSERT INTO T_TEST VALUES (2) ;
INSERT INTO T_TEST VALUES (3) ;
这有效:
DECLARE
vSUM NUMERIC(10) ;
vCOUNT NUMERIC(10) ;
BEGIN
SELECT SUM(TEST) AS SUM INTO vSUM FROM T_TEST ;
DBMS_OUTPUT.PUT_LINE(vSUM) ;
END;
在sp之外,这有效;
SELECT SUM(TEST) AS SUM , COUNT(TEST) AS NB FROM T_TEST ;
但这不是:
DECLARE
vSUM NUMERIC(10) ;
vCOUNT NUMERIC(10) ;
BEGIN
SELECT
SUM(TEST) AS SUM INTO vSUM,
COUNT(TEST) AS NB INTO vCOUNT
FROM T_TEST ;
DBMS_OUTPUT.PUT_LINE(vSUM) ;
DBMS_OUTPUT.PUT_LINE(vCOUNT) ;
END;
答案 0 :(得分:2)
我相信你的语法略有偏差。请尝试以下方法:
DECLARE
vSUM NUMERIC(10);
vCOUNT NUMERIC(10);
BEGIN
SELECT SUM(TEST), COUNT(TEST) -- SELECT and INTO lists should appear
INTO vSUM, vCOUNT -- grouped together separately
FROM T_TEST;
DBMS_OUTPUT.PUT_LINE(vSUM);
DBMS_OUTPUT.PUT_LINE(vCOUNT);
END;
答案 1 :(得分:0)
您还可以避免变量声明,例如:
BEGIN
for x in (
SELECT
SUM(TEST) sum_o_test
, COUNT(1) count_o_test
FROM T_TEST
) loop
DBMS_OUTPUT.PUT_LINE('sum_o_test:' ||x.sum_o_test);
DBMS_OUTPUT.PUT_LINE('count_o_test:'||x.count_o_test);
end loop;
END;