每行输出返回

时间:2019-03-13 23:46:04

标签: oracle plsql oracle-sqldeveloper

我的目标是返回一个类似“星球大战可用:货架上有11个”的语句,但是当我查询该函数时,我的输出是针对每个电影ID而不是函数输入的那个ID返回该语句。我知道我忽略了一些简单的事情,但是我只需要调用即可提取提供的电影ID的语句。 (使用SQL Developer)

CREATE OR REPLACE FUNCTION QTY_MSG_SF 
    (p_movieID mm_movie.movie_id %TYPE)
    RETURN VARCHAR2 
AS  

lv_message_txt VARCHAR2(50);
lv_title_txt mm_movie.movie_title%TYPE;
lv_qty_num MM_MOVIE.MOVIE_QTY%TYPE;

BEGIN
    SELECT movie_title, movie_qty
    INTO lv_title_txt, lv_qty_num
    FROM mm_movie
    WHERE movie_id = p_movieID;


    IF (lv_qty_num > 0) THEN
        lv_message_txt := (lv_title_txt || ' is available: ' || lv_qty_num || ' on the shelf');
     ELSE
        lv_message_txt := (lv_title_txt || ' is  not available');
    END IF;
RETURN lv_message_txt;

END QTY_MSG_SF;

我的电话:

SELECT qty_msg_sf(2)
FROM mm_movie;

1 个答案:

答案 0 :(得分:0)

  

但是当我查询函数时,我的输出返回该语句   对于每个影片ID,而不仅仅是功能输入的影片ID。我知道   我忽略了一些简单的事情,

您的代码正确,但看起来您可能未正确调用它,或者表中的所有电影ID均相同。请参见下面的代码演示,该示例对我来说可以正常工作。

create  table mm_movie(movie_id number,movie_title varchar2(50), movie_qty number);
/
insert into mm_movie values (1,'WarDogs',11);
insert into mm_movie values (2,'Star War',19);
/
Select * from mm_movie;
/
CREATE OR REPLACE FUNCTION QTY_MSG_SF(p_movieID mm_movie.movie_id %TYPE)
  RETURN VARCHAR2 AS

  lv_message_txt VARCHAR2(50);
  lv_title_txt   mm_movie.movie_title%TYPE;
  lv_qty_num     MM_MOVIE.MOVIE_QTY%TYPE;

BEGIN
  SELECT movie_title,
         movie_qty
  INTO   lv_title_txt,
         lv_qty_num
  FROM   mm_movie
  WHERE  movie_id = p_movieID;

  IF (lv_qty_num > 0)
  THEN
    lv_message_txt := (lv_title_txt || ' is available: ' || lv_qty_num ||
                      ' on the shelf');
  ELSE
    lv_message_txt := (lv_title_txt || ' is  not available');
  END IF;
  RETURN lv_message_txt;

END QTY_MSG_SF;

执行

SQL>Select QTY_MSG_SF(2) from dual;

Col
---
Star War is available: 19 on the shelf

SQL>Select QTY_MSG_SF(1) from dual;

Col
---
WarDogs is available: 11 on the shelf