简体   繁体   中英

regular expressions inside a SQL IF statement

I know I can create basic comparison triggers (see below)

CREATE TRIGGER HospitalCheck
BEFORE INSERT ON Hospital
FOR EACH ROW
 BEGIN
  IF NEW.HospitalID > 9999 THEN
     call fail('HOSPITAL CODE INVALID');
  END IF;    
END

How would I go about using a regular expression that only allowed numbers? (instead of the >9999) (the equivalent of SELECT string to check REGEXP '^[0-9]+$')

I tried:

IF NEW.HospitalID REGEX '^[0-9]+$' THEN 
  call fail('HOSPITAL CODE INVALID'); 
END IF;

But i get

: ERROR : --> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REGEX '^[0-9]+$' THEN call fail('HOSPITAL CODE INVALID'); END IF' at line 5

IF NOT column_name REGEXP '^[0-9]+$' THEN

NOT_REGEXP 函数 - 请参阅文档http://dev.mysql.com/doc/refman/5.1/en/regexp.html

IF colname NOT_REGEXP '^[0-9]+$' THEN

Just change the regular expression

IF NEW.HospitalID REGEX '^[^0-9]+$' THEN 
  call fail('HOSPITAL CODE INVALID'); 
END IF;

Explaination

  1. The first caret character is for the start of the HospitalID.
  2. the square bracket [ is for the start of the character class
  3. The second caret character is the nagation of all charecter except zero to 9
  4. the end square bracket is for the end of character class
  5. plus sign character is for that the character class characters must be one or more
  6. the dollar character is for the end of the HospitalID variable.

So in short this regular expression checks the HospitalID variable and if it found that the HospitalID variable had other than numeric characters it call fail function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM