Functions

PL/SQL 語句被忽略

  • August 8, 2020

我真的是 PL/SQL 的新手,我被困在這裡。我想編寫返回的函式allProject

create or replace FUNCTION GETALLPROJECTS RETURN VARCHAR2 AS 
 currentUserID varchar2(10);
BEGIN
SELECT
  p.ProjectID,
  p.CustomName,
  p.Name,
  p.Responsible_person_id,
  p.Delivery_contact,
  p.StartDate,
  p.EndDate,
  p.TehnicReview,
  p.status
INTO currentUserID  
FROM
  projects p
LEFT JOIN
  project_users_schedule_dates pusd
ON
   pusd.ProjectID = p.ProjectID AND 
   pusd.UserID = currentUserID
LEFT JOIN 
   responsible_persons rp
ON 
   rp.ProjectID = p.ProjectID AND 
   rp.UserID = currentUserID
LEFT JOIN 
  users u
ON 
  u.UserID = currentUserID
WHERE
 u.User_roleID = 1
OR 
(
  (p.Responsible_person_id := currentUserID OR 
   p.Delivery_contact = currentUserID OR 
   rp.UserID = currentUserID OR 
  (pusd.ProjectID = p.ProjectID AND                         
  pusd.UserID = currentUserID AND NOW() BETWEEN pusd.StartDate AND pusd.EndDate + INTERVAL 1 DAY 
  AND
  NOW() BETWEEN p.StartDate AND p.EndDate + INTERVAL 1 DAY)
  AND p.status = 2))
GROUP BY 
   p.ProjectID
ORDER BY 
   p.ProjectID 
 RETURN currentUserID;
END GETALLPROJECTS;

我收到錯誤消息,但我不明白問題是什麼:

Error(4,1): PL/SQL: SQL Statement ignored

Error(25,16): PL/SQL: ORA-00920: invalid relational operator

讓我們從一個簡化的例子開始,因為整個複雜的查詢似乎不是問題的一部分。

create or replace function demo
   return varchar2
as
   somevar varchar2(1);
begin
   select dummy into somevar
   from   dual;
   
   return somevar;
end demo;

這將查詢dual表,將列的值提取dummy到局部變數somevar中,並將其作為函式的結果返回。

現在我們可以測試它:

declare
   testvar varchar2(1) := demo();
begin
   dbms_output.put_line('Result is: '||testvar);
end;
/

Result is: X

如果要使用 檢索兩列select into,則需要兩個變數來保存這兩個結果。但是,該函式只能返回一個值,所以我看不出這樣做有什麼意義。

create or replace function demo
   return number
as
   somevar1 varchar2(1);
   somevar2 number;
begin
   select dummy, ascii(dummy) into somevar1, somevar2
   from   dual;
   
   return somevar2;
end demo;

但是,您在頂部提到:

我想編寫返回的函式allProject

是什麼allProject

如果要返回結果集,則返回:

create or replace function demo
   return sys_refcursor
as
   results sys_refcursor;
begin
   open results for
       select dummy
       from   dual;
   
   return results;
end demo;

或者,您可以將結果作為集合返回(這稱為表函式)。

這些方法中哪種方法最好取決於是什麼allProject以及您需要如何使用它。

引用自:https://dba.stackexchange.com/questions/273377