Oracle SQL,用户定义的函数不会在SELECT语句中运行,但如果 Package 在过程中,则会运行

bfhwhh0e  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(91)

我在选民登记册上有一个甲骨文数据库。为了检查一个投票者是否曾经投票过,我创建了一个函数PreviouslyVoted(election_code, electorate_code, voter_id),如下所示。

create or replace FUNCTION previouslyVoted(election_code_in IN NUMBER, electorate_id_in IN NUMBER, voter_id_in IN NUMBER)
RETURN BOOLEAN IS
voter_id_temp NUMBER;
BEGIN
    SELECT COUNT(*) INTO voter_id_temp
    FROM ballot_issuance bi
    WHERE bi.electorate_id = electorate_id_in
    AND bi.election_serial_number = election_code_in
    AND bi.voter_id = voter_id_in;

RETURN voter_id_temp > 0 ;
END;

现在我想从PHP服务器调用它。
我尝试运行发送以下查询:

Select previouslyVoted(" .ELECTION ."," .ELECTORATE .", $oracle_voter_id) "Result" FROM dual;

但没有成功。下面的错误是ERROR:

ORA-00902: invalid datatype
00902. 00000 -  "invalid datatype"
*Cause:    
*Action:
Error at Line: 1 Column: 8

我试着去sqldeveloper和运行

Select previouslyVoted(20190404,1,13321) "Result" FROM dual;

又犯了同样的错误。我试着把表达式扩展到

SELECT
    "S4026115"."PREVIOUSLYVOTED"(20190404, 1, 13321) "Result"
FROM
    "SYS"."DUAL" "A1";

但再次得到同样的错误。有趣的是:如果我把它 Package 在一个像下面这样的过程,它完全正常工作.

create or replace PROCEDURE runprevvoted
AS
   has_voted BOOLEAN;
BEGIN
   has_voted := previouslyVoted(20190404, 1, 13321);
   IF has_voted THEN
      DBMS_OUTPUT.PUT_LINE('This voter has previously voted.');
   ELSE
      DBMS_OUTPUT.PUT_LINE('This voter has not previously voted.');
   END IF;
END;

希望有人能帮助我了解我做错了什么!提前感谢您

zpf6vheq

zpf6vheq1#

你在问题的开头调用了一个函数“previouslyVoted”,但在 Package 器中引用了“has_voted”。我猜它们是一样的问题很可能是函数返回布尔值,而SQL在23 c之前没有布尔数据类型。pl/sql有一个boolean数据类型。因此,发生的情况是pl/sql函数成功执行,但SQL语句出错,因为它不知道数据类型。
范例:

koen19c>set serveroutput on size 999999
koen19c>CREATE OR REPLACE FUNCTION istrue RETURN BOOLEAN
  2  AS
  3  BEGIN
  4    RETURN true;
  5  END;
  6* /

Function ISTRUE compiled

koen19c>BEGIN 
  2    IF istrue() THEN
  3      dbms_output.put_line('it is true !');
  4    END IF;
  5  END;
  6* /
it is true !

PL/SQL procedure successfully completed.

koen19c>SELECT istrue() from dual;

Error starting at line : 1 in command -
SELECT istrue() from dual
Error at Command Line : 1 Column : 8
Error report -
SQL Error: ORA-00902: invalid datatype
00902. 00000 -  "invalid datatype"
*Cause:    
*Action:
koen19c>

解决方案,修改函数,使其返回字符串('Y'/'N','true'/'false')或数字(1/0)

相关问题