【问题标题】:I'm trying to turn selection into function in Toad/Oracle我正在尝试将选择转变为 Toad/Oracle 中的功能
【发布时间】:2019-01-07 07:32:13
【问题描述】:

我正在尝试将此选择转化为功能。 而不是 sysdate 用户将给出他自己想要查看的日期。 (抱歉英语不好)。

SELECT  trunc(sysdate),
        trunc(sysdate) - 1,
        trunc(sysdate) - 2,
        trunc(sysdate) - 3,
        trunc(last_day(sysdate)-1, 'mm'),       
        add_months(trunc(sysdate, 'MM'), -1) first_day_of_last_month,
        add_months(trunc(sysdate, 'MM'), -2) first_day_of_last_month,
        add_months(trunc(sysdate, 'MM'), -3) first_day_of_last_month,
        add_months(trunc(sysdate, 'Q'), -6) first_day_of_last_quarter,
        add_months(trunc(sysdate, 'Q'), -9) first_day_of_last_quarter,
        add_months(trunc(sysdate, 'Q'), -12) first_day_of_last_quarter,
        add_months(trunc(sysdate, 'Q'), -15) first_day_of_last_quarter,
        add_months(trunc(sysdate, 'Q'), -18) first_day_of_last_quarter
FROM dual;

结果在 1 Row 中应该是这样的

1/7/2019    1/6/2019    1/5/2019    1/4/2019    1/1/2019    12/1/2018   11/1/2018   10/1/2018   7/1/2018    4/1/2018    1/1/2018    10/1/2017   7/1/2017

【问题讨论】:

  • 直接把它变成一个函数,是什么阻止了你?
  • 你希望从函数中返回什么?你想返回一个游标吗?您希望它作为流水线表函数返回吗?在我们提出任何具体建议之前,需要更多详细信息。
  • 我的主要问题是我不知道如何在函数中返回多个值,而不是 sysdate 用户将给出自己的日期,函数应该返回 1 行具有多个值。
  • 为什么是trunc(last_day(pdt_ref_date)-1, 'mm')?这将始终与trunc(pdt_ref_date, 'mm') 相同
  • @Boneist 好吧,我是新手,我不知道。感谢您的回复

标签: sql oracle plsql stored-functions


【解决方案1】:

您可以构建一个返回引用光标的函数。

CREATE FUNCTION get_dates(pdt_ref_date IN DATE)
RETURN SYS_REFCURSOR IS
    pcr_result SYS_REFCURSOR;
BEGIN
    OPEN pcr_result FOR
    SELECT  
        trunc(pdt_ref_date),
        trunc(pdt_ref_date) - 1,
        trunc(pdt_ref_date) - 2,
        trunc(pdt_ref_date) - 3,
        trunc(last_day(pdt_ref_date)-1, 'mm'),       
        add_months(trunc(pdt_ref_date, 'MM'), -1) first_day_of_last_month,
        add_months(trunc(pdt_ref_date, 'MM'), -2) first_day_of_last_month,
        add_months(trunc(pdt_ref_date, 'MM'), -3) first_day_of_last_month,
        add_months(trunc(pdt_ref_date, 'Q'), -6) first_day_of_last_quarter,
        add_months(trunc(pdt_ref_date, 'Q'), -9) first_day_of_last_quarter,
        add_months(trunc(pdt_ref_date, 'Q'), -12) first_day_of_last_quarter,
        add_months(trunc(pdt_ref_date, 'Q'), -15) first_day_of_last_quarter,
        add_months(trunc(pdt_ref_date, 'Q'), -18) first_day_of_last_quarter
    FROM dual;

    RETURN pcr_result;
END;

可以通过以下方式使用:

SELECT get_dates(SYSDATE)
FROM DUAL;

注意:

  • 我不知道这个函数的用途,所以我一般称它为 get_dates
  • 您可能需要在包中定义此函数, 特别是如果您有几个相关的功能/过程

【讨论】:

  • 感谢您的回复。此功能的目的是用于每日、每月、季度财务报告。用户将给出他的日期并显示报告的日期。目前我正在使用 Toad 并且“无效的 SQL 语句”这个错误显示我该如何解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 2019-07-26
相关资源
最近更新 更多