如何检查时间是否大于或小于 PLSQL 中的另一个时间

How to check if time is greater or less than another time in PLSQL

如果插入的记录在 table TUTPRAC 包含和 CLASSTIME < '9AM' OR > '6PM' 中,我正在尝试检查我的触发器。如果这是真的,那么该记录将被更新,某些字段被更改为 NULL.

CREATE TRIGGER CheckBeforeAfterHours
BEFORE INSERT OR UPDATE OF CLASS_TIME ON TUTPRAC
FOR EACH ROW
BEGIN
  IF (:NEW.CLASS_TIME < '09:00' OR > '18:00') THEN
     :NEW.STAFFNO := NULL;
     :NEW.CLASS_DAY := NULL;
     :NEW.CLASS_TYPE := NULL;
     :NEW.ROOMNUM := NULL;
  END IF;
END CheckBeforeAfterHours;

TUTPRAC的列table:

CLASSID (PK), UNITCODE, STAFFNO, CLASSDAY, CLASSTIME, CLASSTYPE, ROOMNUM

字段 CLASSTIME 设置为 varchar(5)

我用Oracle SQLDeveloper.

问题

我的问题是,当我尝试 运行 触发器时,我不断收到此错误:

Error(2,36):
PLS-00103: Encountered the symbol ">" when expecting one of the following:
    ( - + case mod new not null <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> continue avg count current exists max min prior sql stddev
    sum variance execute forall merge time timestamp interval
    date <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    <an alternatively-quoted string literal with character set specification>
    <an alternatively

正确的语法是:

IF (:NEW.CLASS_TIME < '09:00' OR :NEW.CLASS_TIME > '18:00') THEN

这里有两个问题:

IF (:NEW.CLASS_TIME < '09:00' OR > '18:00')

语法不正确。您还需要在 OR 条件中提及 :NEW.CLASS_TIME

The field "CLASSTIME" is set to varchar(5)

那么你应该进行数字比较而不是字符串比较。字符串比较基于 固定格式,它根据 ASCII 值而不是纯数字进行比较。

假设您传递 5:00 而不是 05:00,即当格式不固定时,比较将给出不同的输出,因为 ASCII 值会有所不同。

SQL> SELECT ascii('05:00'), ascii('5:00') FROM dual;

ASCII('05:00') ASCII('5:00')
-------------- -------------
            48            53

设置

SQL> CREATE TABLE t(A VARCHAR2(5));

Table created.

SQL> INSERT INTO t VALUES('04:00');

1 row created.

SQL> INSERT INTO t VALUES('05:00');

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

A
-----
04:00
05:00

字符串比较

SQL> SELECT * FROM t WHERE a < '5:00';

A
-----
04:00
05:00

SQL> SELECT * FROM t WHERE a < '05:00';

A
-----
04:00

那么上面发生了什么? '05:00''5:00' 不一样。为避免这种混淆,最好进行数字比较。

SQL> SELECT * FROM t WHERE TO_NUMBER(SUBSTR(a, 2, 1)) < 5;

A
-----
04:00

SUBSTR 将提取数字部分,TO_NUMBER 将其显式转换为数字。