开发者

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 correspo开发者_开发知识库nds 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


NOT_REGEXP function - see the docs http://dev.mysql.com/doc/refman/5.1/en/regexp.html

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


IF NOT column_name 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜