【问题标题】:SQL trigger DATEPART is not declaredSQL 触发器 DATEPART 未声明
【发布时间】:2020-04-10 09:44:57
【问题描述】:

我正在尝试创建一个触发器,如果​​当前时间在晚上 10 点到早上 6 点之间,它会提示错误消息。这是我写的代码:

CREATE OR REPLACE TRIGGER horarioModificar 
BEFORE UPDATE ON employees
FOR EACH ROW
DECLARE
   horaActual NUMBER:= DATEPART(hour, SYSDATETIME());
BEGIN 
    IF  horaActual < 6 OR horaActual > 22 THEN
        raise_application_error(-20250,'No se puede realizar ningún cambio entre las 22:00 y las 6:00');
    END IF;
END;
/

我收到一条错误消息,提示需要声明 DATEPART(错误代码 PLS-00201)。有人知道我的代码有什么问题吗?

【问题讨论】:

  • 如果您为特定的 rdbms 添加标签(例如 mysqlsql-server)会有所帮助。日期时间功能因这些系统而异。
  • 我添加了oracle标签,因为错误代码PLS-00201表示这是您正在运行的数据库。

标签: sql oracle date database-trigger datepart


【解决方案1】:

您收到的错误消息 (PLS-00201) 表明您正在运行 Oracle。

下面是可在 Oracle 上运行的新版本触发器代码:

create or replace trigger horariomodificar 
before update on employees 
for each row 
begin 
    if not extract(hour from systimestamp) between 6 and 22 
        then raise_application_error(
            -20250,
            'no se puede realizar ningún cambio entre las 22:00 y las 6:00'
        ); 
    end if; 
end; 
/

值得注意的点:

  • datepart() 在 Oracle 中不存在(这是一个 SQL Server 函数);您可以使用extract(hour from systimestamp) 获取当前时间

  • 你真的不需要使用变量,所以我删除了它

  • 这段代码实际上阻止了 23h 和 6h 之间的变化,而不是 22h 和 6h 之间的变化;否则,你想要:if not extract(hour from systimestamp) not between 6 and and 21

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2016-12-16
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多