如何创建pl sql函数以检查数据库中是否存在数据

时间:2020-01-25 07:08:22

标签: sql database function plsql compiler-errors

我正在尝试创建一个函数来告诉数据库中是否存在数据。如果存在数据,则尝试使用游标解决此问题,然后将从数据库中获取数据,并且temp的值为TRUE,否则将不会从DB中获取数据,并将temp的值设置为false。 / p>

但是当我编译此函数时,它会发出警告

警告:函数创建时出现编译错误。

CREATE OR REPLACE FUNCTION CHECK_DATA(Eid IN varchar2(5))
RETURN boolean 
IS 
    cursor cemp is select EMPNO from employee where EMPNO = Eid ;
    eno employee.EMPNO%TYPE ;
    temp number;
BEGIN 
    open cemp ;
    fetch cemp into eno ;
    if(cemp%notfound)then
        temp := FALSE ;
    else 
        temp := TRUE ;
    End if ;
    close cemp ;
    return temp ;
END; 
/

3 个答案:

答案 0 :(得分:0)

您可以像这样Reference

使用光标
 DECLARE

       CURSOR cCheck (p_Param IN NUMBER) IS

          SELECT /*+ FIRST_ROWS */ 99

          FROM   my_table

          WHERE  some_column = p_Param

          FOR UPDATE; 

       v_dummy       NUMBER;

       v_row_exists  BOOLEAN;



       v_test    NUMBER := 1;  -- This would actually come from a parameter or somewhere

    BEGIN



       OPEN cCheck(v_test);

       FETCH cCheck INTO v_dummy;

       v_row_exists := cCheck%FOUND;

       CLOSE cCheck;



       IF v_row_Exists THEN

          ... Do something that can't be done with MERGE

       END IF;

       CLOSE cCheck;

答案 1 :(得分:0)

我建议使用implicit光标,不要打扰打开/关闭;

CREATE OR REPLACE FUNCTION CHECK_DATA(Eid IN varchar2(5)) RETURN boolean IS 
  n number;
BEGIN 
 select count(*) into n
 from employee where EMPNO = Eid ;
 if (n > 0) then
   return true;  
 else
    return false;
 end if;
END; 
/

答案 2 :(得分:0)

另一种方式

CREATE OR REPLACE 
function CHECK_DATA(Eid IN varchar2(5)) return boolean is PRAGMA AUTONOMOUS_TRANSACTION;
Begin
Declare
n integer;
begin
    execute immediate 'select count(*) from employee where EMPNO ='||Eid||'' into n;
   if n > 0 then
     return true;  
   else
     return false;
   end if;
end;
End;
/
相关问题