我正在尝试学习PL / SQL,但我似乎不明白如何创建函数并让它返回记录。
我正在尝试做这样的事情:
create or replace FUNCTION getMovie(movieID number)
RETURN record IS titleAndYear record(title varchar(100), production_Year number);
BEGIN
if (titleAndYear is null) then
titleAndYear:= MovieTitleAndYear('',0);
end if;
select TITLE ,YEAR into titleAndYear.title ,titleAndYear.production_Year from movie where MOVIE_ID = movieID;
return titleAndYear;
END;
我知道这行不通,但我不知道为什么?
编辑1:我也试过这个:
create or replace TYPE MovieTitleAndYear is OBJECT(title varchar(100), production_Year number);
/
create or replace FUNCTION getMovie(movieID number)
RETURN MovieTitleAndYear IS titleAndYear MovieTitleAndYear;
BEGIN
if (titleAndYear is null) then
titleAndYear:= MovieTitleAndYear('',0);
end if;
select TITLE ,YEAR into titleAndYear.title ,titleAndYear.production_Year from movie where MOVIE_ID = movieID;
return titleAndYear;
END;
但是然后当我运行此语句时的结果:
select
GETMOVIE(
2540943
) from dual;
变成这个
GETMOVIE(2540943)
1 [DB_036.MOVIETITLEANDYEAR]
而不是两个专栏标题和制作年份。
您使用记录的第一个示例将不起作用。首先,函数不能返回仅在函数内部声明的类型的值。您可以尝试将记录类型声明移动到包中,但是即使您随后获得了要编译的功能,运行查询select getMovie(2540943) from dual
也将返回ORA-00902 invalid datatype
错误。
因此,我建议您改用类型。
如果使用的是类型,则要分别获取电影和年份,需要分别访问类型中的字段,例如:
select getMovie(2540943).title, getMovie(2540943).production_year from dual
另外,如果要避免调用getMovie()
两次,可以使用子查询:
select x.movie_info.title, x.movie_info.production_year from (select getMovie(2540943) as movie_info from dual) x;
请注意,我们需要为子查询使用别名。以下将给出ORA-00904: "MOVIE_INFO"."PRODUCTION_YEAR": invalid identifier
错误:
select movie_info.title, movie_info.production_year from (select getMovie(2540943) as movie_info from dual);
这里的问题是Oraclemovie_info
在查询中查找表,但找不到表。它没有意识到这movie_info
实际上是一列。如果我们引入别名x
,那么Oracle将意识到这x.movie_info
是一列,因此x.movie_info.title
该列中的类型内的字段也是如此。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句