【问题标题】:How to check if time is greater or less than another time in PLSQL如何检查时间是否大于或小于PLSQL中的另一个时间
【发布时间】:2015-10-24 15:37:23
【问题描述】:

如果插入的记录在表 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 表的列:

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

【问题讨论】:

    标签: oracle syntax plsql date-comparison database-trigger


    【解决方案1】:

    正确的语法是:

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

    【讨论】:

    • 它依赖于固定格式来确保 ascii 转换给出正确的输出。
    【解决方案2】:

    这里有两个问题:

    IF (:NEW.CLASS_TIME '18:00')

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

    “CLASSTIME”字段设置为 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 将其显式转换为数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多