我是pl / sql的新手。我想要 进行程序检查表员工是否存在empno emno大于100。如果存在至少一个,我想要 退出循环。
如何修改以下代码? 是不是我不知道;使用%NOTFOUND,%ROWCOUNT?
CREATE OR REPLACE procedure check_value
IS
cursor c1 is
select *
from employess;
c1_values c1%ROWTYPE;
BEGIN
open c1;
fetch c1 into c1_values;
loop
if c1_values.EMPNO > 100 then
DBMS_OUTPUT.put_line ('Found row with empno > 100');
end if;
end loop;
close c1;
END;
提前感谢您的帮助。
答案 0 :(得分:1)
如果你只是需要检查你是否拥有超过100的记录,你可以使用EXISTS
声明,例如
DECLARE
CURSOR c1 IS
SELECT
CASE
WHEN EXISTS (
SELECT
1
FROM
employees
WHERE
empno > 100
) THEN 1
ELSE 0
END AS empno_exists
FROM
dual;
ln_empno_exists PLS_INTEGER;
BEGIN
OPEN c1;
FETCH c1 INTO ln_empno_exists;
CLOSE c1;
DBMS_OUTPUT.PUT_LINE('Empno over 100 exists: '||CASE WHEN ln_empno_exists = 1 THEN 'TRUE' ELSE 'FALSE' END);
END;
/
编辑:如果您想在某些条件下获取行,则只需在WHERE
语句中调整SELECT
子句即可。这里有一个示例,通过一些方法来迭代所提取的记录:
DECLARE
CURSOR c1 IS
SELECT
emp.*
FROM
employees emp
WHERE
empno > 100
;
lr_c1_rec c1%ROWTYPE;
BEGIN
-- Using FOR loop
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
FOR rec IN c1
LOOP
DBMS_OUTPUT.PUT_LINE('empno = '||rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
-- Using a LOOP with EXIT clause
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
OPEN c1;
LOOP
FETCH c1 INTO lr_c1_rec;
-- exit the loop when your cursor doesn't have any more records to be returned
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('empno = '||lr_c1_rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
-- Using WHILE loop
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
OPEN c1;
FETCH c1 INTO lr_c1_rec;
-- As long as cursor returns any values, iterate through the records returned
WHILE c1%FOUND
LOOP
DBMS_OUTPUT.PUT_LINE('empno = '||lr_c1_rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
END;
/
答案 1 :(得分:0)
只需在找到您的价值后添加EXIT
声明:
CREATE OR REPLACE procedure check_value IS
cursor c1 is
select *
from employess;
c1_values c1%ROWTYPE;
BEGIN
open c1;
loop
fetch c1 into c1_values;
IF c1%NOTFOUND THEN EXIT;
if c1_values.EMPNO > 100 then
DBMS_OUTPUT.put_line ('Found row with empno > 100');
EXIT;
end if;
end loop;
-- The EXIT statement will drop you out of the loop and leave you here
close c1;
END;
请注意,我在循环中移动了fetch
并添加了%NOTFOUND检查。如果没有%NOTFOUND,代码永远不会知道光标没有数据,可能会进入无限循环。
答案 2 :(得分:0)
为什么要定义游标,然后打开并获取它只需要完成 SQL但如果需要,那么使用FOR循环和EXIT条件 如上所述
下方。希望它有所帮助
CREATE OR REPLACE PROCEDURE check_value
IS
BEGIN
FOR I IN
(SELECT * FROM employess
)
LOOP
IF I.EMPNO > 5 THEN
DBMS_OUTPUT.put_line ('Found row with empno > 100');
EXIT;
END IF;
END LOOP;
END;