【问题标题】:Oracle - Function to return a query result based on parameterOracle - 根据参数返回查询结果的函数
【发布时间】:2013-11-26 00:42:31
【问题描述】:

我正在尝试编写一个 Oracle PL/SQL 函数,该函数将返回应用程序的给定 status_id,因此如果返回的 status_type 是特定值,我可以将数据归档到历史表中。

在本例中,我的状态类型是“已批准”、“待定”或“已拒绝”

到目前为止,我已经编写了这个函数,以便我可以在 IF 语句中运行该方法,以便在归档数据之前检查当前状态类型。

CREATE OR REPLACE FUNCTION get_status(curr_id NUMBER)
RETURN VARCHAR2 AS this_type status_type;

BEGIN
    SELECT status_type 
    INTO this_type
    FROM status
    WHERE status_id LIKE curr_id;

    RETURN this_type;
END get_status;

虽然它可以编译,但我收到一条错误消息,告诉我我的 PL/SQL 语句已被忽略。
我对 Oracle 很陌生,所以我可能在这里遗漏了一些简单的东西,谁能给我任何关于我的代码哪里出错的指针?

提前致谢, 亚历克斯。

【问题讨论】:

  • 你能分享一下错误吗?
  • 当然:错误(2,31):PLS-00201:必须声明标识符“STATUS_TYPE”并且错误(5,3):PL/SQL:SQL 语句被忽略——据我了解"this_type status_type" 行将 this_type 的别名设置为 status_type(状态表中的列)?

标签: sql oracle


【解决方案1】:
CREATE OR REPLACE FUNCTION get_status(curr_id NUMBER)
RETURN VARCHAR2 
AS 
--%TYPE is used to declare variables with relation to the data type of a column 
--in an existing table 

this_type status.status_type%TYPE; --change is required here 

BEGIN
   SELECT status_type 
   INTO this_type
   FROM status
   WHERE status_id LIKE curr_id;

   RETURN this_type;
END get_status;
/

【讨论】:

  • 啊,我明白了,这很有道理!谢谢高拉夫!
  • 注意: 1. 使用不带通配符的like 条件等同于使用等号。如果不需要进行模式匹配,切换到简单等号; 2. 在不同的情况下,您可以:a)点击not_data_found错误或b)too_many_rows错误。
  • @NicholasKrasnov:你是对的,@Alex:请记住这一点
  • 感谢@NicholasKrasnov 的提醒
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2020-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
相关资源
最近更新 更多