IF语句包含SELECT语句

时间:2016-10-25 12:42:29

标签: oracle plsql

运行时:

    create or replace FUNCTION GET_FUNCTION(STATUS_ID IN VARCHAR2) 
    RETURN VARCHAR2
    IS STATUS_NAME VARCHAR2(255);
    BEGIN 
    IF NVL(STATUS_ID) THEN
          STATUS_NAME:='';
    ELSIF  STATUS_ID LIKE '0' THEN
          STATUS_NAME:='UNASSIGNED'
    ELSE
          SELECT TABLE_A.NAME INTO STATUS_NAME FROM TABLE_A where
    TABLE_A.ID=STATUS_ID;
    END IF;

    RETURN(STATUS_NAME);
    end;

我收到以下错误:

Error(9,4): PLS-00103: Encountered the symbol "ELSE" when expecting one of the following:     
* & = - + ; < / > at in is mod remainder not rem    <an exponent (**)> <> or != or ~= >= <= <> and or like like2    like4 likec between || multiset member submultiset 
The symbol ";" was substituted for "ELSE" to continue. 

有什么问题?

3 个答案:

答案 0 :(得分:0)

CREATE OR REPLACE FUNCTION GET_FUNCTION(STATUS_ID IN VARCHAR2) 
RETURN VARCHAR2
IS STATUS_NAME VARCHAR2(255);
BEGIN 
IF NVL(STATUS_ID) THEN
      STATUS_NAME := '';
ELSIF STATUS_ID = '0' THEN
      STATUS_NAME := 'UNASSIGNED';
ELSE
      SELECT TABLE_A.NAME INTO STATUS_NAME 
      FROM TABLE_A 
      WHERE TABLE_A.ID = STATUS_ID;
END IF;

RETURN STATUS_NAME;
END;

答案 1 :(得分:0)

您需要在每个要执行的语句后添加分号(代码中的第8行 - 我添加了注释):

create or replace FUNCTION GET_FUNCTION(STATUS_ID IN VARCHAR2) 
RETURN VARCHAR2
IS STATUS_NAME VARCHAR2(255);
BEGIN 
IF NVL(STATUS_ID) THEN
      STATUS_NAME:='';
ELSIF  STATUS_ID LIKE '0' THEN
      STATUS_NAME:='UNASSIGNED'; /* HERE HAS TO BE A SEMICOLON TOO */
ELSE
      SELECT TABLE_A.NAME INTO STATUS_NAME FROM TABLE_A where
TABLE_A.ID=STATUS_ID;
END IF;

RETURN(STATUS_NAME);
end;

答案 2 :(得分:0)

我认为这是一个有点迟钝

CREATE OR REPLACE FUNCTION GET_FUNCTION(STATUS_ID IN VARCHAR2) 
RETURN VARCHAR2
IS 
  cursor c_tab (B_STATUS_ID IN TABLE_A.ID%TYPE)
  is
  SELECT TABLE_A.NAME 
  FROM TABLE_A 
  WHERE TABLE_A.ID = B_STATUS_ID;

  STATUS_NAME VARCHAR2(255);
BEGIN 
IF NVL(STATUS_ID, -1) = -1 THEN
-- IF STATUS_ID IS NULL THEN  ==> This one is also possible!
      STATUS_NAME := '';
ELSIF STATUS_ID = '0' THEN
      STATUS_NAME := 'UNASSIGNED';
ELSE
      OPEN C_TAB (STATUS_ID);
      FETCH C_TAB INTO STATUS_NAME;
      CLOSE C_TAB;
END IF;

RETURN STATUS_NAME;
END;